問題描述
C++ 標(biāo)準(zhǔn) [sec 5.7] 說:
The C++ standard [sec 5.7] says:
如果指針操作數(shù)和結(jié)果都指向同一個數(shù)組對象的元素,或者一個過去數(shù)組對象的最后一個元素,求值不應(yīng)產(chǎn)生溢出;否則,行為是未定義.
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.
那么,我是否正確地假設(shè)數(shù)組以外的其他類型的指針未定義?
So, am I correct in assuming that pointers one-past-the-end of other types than arrays are undefined?
例如:
int a = 0;
vector<int> v(&a, (&a)+1);
上面的代碼片段編譯并運(yùn)行得很好(使用 g++),但它有效嗎?
The above snippet compiles and works just fine (with g++), but is it valid?
推薦答案
不,這是合法的.5.7(4) - 您引用前的一段 - 說:就這些運(yùn)算符而言,指向非數(shù)組對象的指針的行為與指向長度為 1 的數(shù)組的第一個元素,以對象的類型作為其元素類型."
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."
這篇關(guān)于是“一過即盡"嗎?非數(shù)組類型的指針是 C++ 中的有效概念嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!