Is the “one-past-the-end” pointer of a non-array type a valid concept in C++?

徘徊边缘 提交于 2019-12-17 06:49:48

问题


The C++ standard [sec 5.7] says:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

So, am I correct in assuming that pointers one-past-the-end of other types than arrays are undefined?

For example:

int a = 0;
vector<int> v(&a, (&a)+1);

The above snippet compiles and works just fine (with g++), but is it valid?


回答1:


No, it is legal. 5.7(4) - one paragraph before your quote - says: "For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type."



来源:https://stackoverflow.com/questions/14505851/is-the-one-past-the-end-pointer-of-a-non-array-type-a-valid-concept-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!