将具有整数类型的表达式添加或减去时
从指针开始,结果具有指针操作数的类型.如果
指针操作数指向数组对象的元素,并且该数组
足够大,结果指向的元素与
原始元素,使得
结果数组元素和原始数组元素等于整数表达式.
换句话说,如果表达式指向
数组对象,表达式(P)+N
(等效于N+(P))
和
(P)-N
(其中N
具有值n)分别指向
数组对象的i+n-th
和i−n-th
元素,前提是它们
存在.此外,如果表达式P
指向的最后一个元素
一个数组对象,表达式(P)+1
指向最后一个
数组对象的元素,如果expressionQpoints指向
数组对象的最后一个元素,表达式(Q)-1
指向
arrayobject的最后一个元素.如果指针操作数和
结果指向同一数组对象的元素,或
数组对象的最后一个元素,求值不应产生
溢出;否则,行为是不确定的
When an expression that has integral type is added to or subtracted
from a pointer, the result has the typeof the pointer operand. If the
pointer operand points to an element of an array object, and the array
islarge enough, the result points to an element offset from the
original element such that the difference ofthe subscripts of the
resulting and original array elements equals the integral expression.
In other words, if the expression points to the i-th
element of an
array object, the expressions (P)+N
(equivalently, N+(P))
and
(P)-N
(where N
has the valuen) point to, respectively, the
i+n-th
and i−n-th
elements of the arrayobject, 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 expressionQpointsone past the
last element of an array object, the expression (Q)-1
points to the
last element of the arrayobject. 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
如果为gcc打开迭代器调试,则可以验证这一点
You can verify this if you turn on iterator debugging for gcc
# g++ main.cpp -D_GLIBCXX_DEBUG -o main
# ./main
C:/mingw-w64/i686-8.1.0-win32-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/debug/safe_iterator.h:374:
Error: attempt to advance a dereferenceable (start-of-sequence) iterator 10
steps, which falls outside its valid range.
Objects involved in the operation:
iterator @ 0x0061FE3C {
type = __gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<int*, std::__cxx1998::vector<int, std::allocator<int> > >, std::__debug::vector<int, std::allocator<int> > > (mutable iterator);
state = dereferenceable (start-of-sequence);
references sequence with type 'std::__debug::vector<int, std::allocator<int> >' @ 0x0061FE50
}
这篇关于限制迭代器是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!