的操作语义operator+(n)
,对于随机访问迭代器来说是这样的[随机访问迭代器],表 99 *:
difference_type m = n;
if (m >= 0)
while (m--)
++r;
else
while (m++)
--r;
return r;
And for ++r
前提是[输入.迭代器],表 95 *:
前提条件:r
是可解引用的。
With begin() + n
从某个值开始,这个前提条件将不会得到满足m
if n
大于容器的尺寸。后begin + 10;
你已经有了 UB,其余的代码是无关紧要的。
GCC 标准库清理程序(编译为-D_GLIBCXX_DEBUG
)会给你以下错误:
/usr/include/c++/10/debug/safe_iterator.h:885:
In function:
__gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<int*,
std::__cxx1998::vector<int, std::allocator<int> > >,
std::__debug::vector<int>, std::random_access_iterator_tag>::_Self
__gnu_debug::operator+(const _Self&,
__gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<int*,
std::__cxx1998::vector<int, std::allocator<int> > >,
std::__debug::vector<int>,
std::random_access_iterator_tag>::difference_type)
Error: attempt to advance a dereferenceable (start-of-sequence) iterator 10
steps, which falls outside its valid range.
Objects involved in the operation:
iterator @ 0x0x7fffffffb900 {
type = __gnu_cxx::__normal_iterator<int*, std::__cxx1998::vector<int, std::allocator<int> > > (mutable iterator);
state = dereferenceable (start-of-sequence);
references sequence with type 'std::__debug::vector<int, std::allocator<int> >' @ 0x0x7fffffffb8c0
}
- N4659(2017 年 3 月 Kona 工作草案/C++17 DIS)