是“一过即尽"吗?非数组类型的指针是 C++ 中的有效概念吗? [英] Is the "one-past-the-end" pointer of a non-array type a valid concept in C++?

查看:28
本文介绍了是“一过即尽"吗?非数组类型的指针是 C++ 中的有效概念吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++ 标准 [sec 5.7] 说:

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?

例如:

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

上面的代码片段编译并运行得很好(使用 g++),但它有效吗?

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

推荐答案

不,这是合法的.5.7(4) - 您引用前的一段 - 说:就这些运算符而言,指向非数组对象的指针的行为与指向长度为 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."

这篇关于是“一过即尽"吗?非数组类型的指针是 C++ 中的有效概念吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆