The operational semantics of operator+(n)
, for a random access iterator is this [random.access.iterators], Table 99 *:
difference_type m = n;
if (m >= 0)
while (m--)
++r;
else
while (m++)
--r;
return r;
And for ++r
the precondition is [input.iterators], Table 95 *:
Preconditions: r
is dereferenceable.
With begin() + n
this precondition will not be satisfied starting from some value of m
if n
is greater than the size of the container. After begin + 10;
you already have UB, and the rest of the code is irrelevant.
GCC standard library sanitizer (compile with -D_GLIBCXX_DEBUG
) will give you the following error:
/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 (March 2017 post-Kona working draft/C++17 DIS)