Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 字符串s&;s+;1.合法的乌兰巴托?_C++_Undefined Behavior - Fatal编程技术网

C++ 字符串s&;s+;1.合法的乌兰巴托?

C++ 字符串s&;s+;1.合法的乌兰巴托?,c++,undefined-behavior,C++,Undefined Behavior,考虑以下代码: #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { string myAry[] = { "Mary", "had", "a",

考虑以下代码:

#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    string myAry[] = 
    {
        "Mary",
        "had", 
        "a",
        "Little",
        "Lamb"
    };
    const size_t numStrs = sizeof(myStr)/sizeof(myAry[0]);

    vector<string> myVec(&myAry[0], &myAry[numStrs]);

    copy( myVec.begin(), myVec.end(), ostream_iterator<string>(cout, " "));

    return 0;
}

该规范是否合法且定义明确?将数组元素的地址移过末尾是合法且定义明确的,如
&myAry[numStrs]
中所述,那么假装
myPtr
也是数组也是合法且定义明确的吗?

将指针移到数组的“一端”是合法的,而不是UB,任何单个对象都可以被视为长度为1的数组;但是,由于
&ptr[1]
解引用然后获取地址的技术性,您需要使用
ptr+1
。这也适用于
&array[size]
成为
array+size

你所期望的所有工作都会在我所知道的所有平台上运行,但是如果使用简单明确的形式是多么容易,我看没有理由不这样做。

< P> 5.6/4的“加性运算符”中的C++标准说:

对于这些运算符,指向非数组对象的指针的行为与指向长度为1且对象类型为其元素类型的数组的第一个元素的指针的行为相同


C99标准6.5.6/7基本相同。

+1表示技术准确性。这不仅很容易做到正确,而且还避免了由于
操作符&
被重载而带来的更多陷阱(是的,重载是不好的。但这说明了如何拖拽依赖项)。最好不要有未定义的行为。
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    string myStr = "Mary";
    string* myPtr = &myStr;
    vector<string> myVec2(myPtr, &myPtr[1]);

    copy( myVec2.begin(), myVec2.end(), ostream_iterator<string>(cout, " "));   

    return 0;
}