c++ - 递增迭代器超出范围

标签 c++

递增随机访问迭代器超出范围是否非法? 事实证明,vector 的 Visual C++ 实现触发了调试断言。

std::vector<int> foo(5);
auto iter = foo.begin();
iter += 10;

只要不评估内存位置,这对指针来说应该是合法的。

编辑:显然即使使用指针也是非法的。

最佳答案

这是未定义的行为。都有迭代器和指针。和 迭代器,您可能会遇到断言失败,至少 迭代器调试打开。有了指针,它可能会做 在大多数现代建筑中什么都没有,但已经有机器 它可以在陷阱处触发。您不必访问内存 位置本身,只需创建指针,用于未定义的行为 发生。

编辑:

来自标准(§5.7/5,添加了强调):

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i − n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. 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.

随机访问迭代器的相应规则(唯一的那些 支持添加)分布在几个部分:+= 运算符 是根据重复的 ++ 定义的(对于语义——它是 要求具有恒定的时间复杂度),并且 ++ 具有要求 “pre: r 是可取消引用的。发布:r 是可取消引用的或 r 已经过去了。” (根据输入迭代器的定义, 由前向迭代器继承,由双向继承 迭代器,由随机访问迭代器继承)。

关于c++ - 递增迭代器超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28408649/

相关文章:

c++ - 使用 C++ 修复 .txt 文件中的列宽

c++ - C++文件读取错误

c++ - 如何在 C++ 中为枚举重载++ 运算符

c++ - GCC/G++ 地址和无法读取寄存器

c++ - 如何在Qt5 C++中使用QMediaRecorder从QImage序列生成视频文件

python - 将 Qt 嵌入 native 窗口 (Windows)

c++ - 如何在 C++ 中跨实例调用方法

C++ Libcurl 无法清除 header

c++ - 在不使用内核的情况下写入 CUDA 中的共享内存

c++ - 打印余数时丢失 0