Is the quot;one-past-the-endquot; pointer of a non-array type a valid concept in C++?(是“一过即尽吗?非数组类型的指针是 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++ 中的有效概念吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是“一过即尽"吗?非数组类型的指针是 C++ 中
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
