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++ 中


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01