Feng Shu Feng Shu - 2 months ago 22
C++ Question

Why std::vector iterator is invalidated after the erase() call?

The C++ reference clearly state that calling

on iterator will invalidate all iterators pointing to and after the erased element. http://en.cppreference.com/w/cpp/container/vector/erase

I do understand why such iterators became non-dereferenceable after the
call, but i am curious why they need to became invalid, what implementation details require it?

For instance standard says that
must be implemented with elements stored contiguously and that
elements can be accessed not only through iterators, but also using offsets on regular pointers to elements
so it seems logical that iterators for such container will probably be implemented as pointers - but then how pointers could became invalidated?


One of the principles on which the conceptual idea of iterator is built, is as follows: as long as iterator remains non-aliased, dereferenceable and non-modified, it should refer to the same entity. In other words, dereferencing the same iterator multiple times should yield the same value. Algorithms that use iterators may rely on that.

What you proposing would result in an iterator that would "magically" change the value it refers to even though the iterator itself remains unchanged. This is not acceptable within the conceptual idea of iterator.