You seem to think of the “invalid” iterator as something that might cause a crash when using, but the standard definition is wider. It includes the possibility that the iterator can be dereferenced safely, but no longer indicates the element to which it should refer. (This is a special case of observing that “undefined behavior” does not mean that “your program immediately crashes”, it may also mean that “your program will silently calculate the wrong result” or even “nothing observable will happen incorrectly on this implementation. ")
It is easier to demonstrate why this is a problem with erase :
#include <vector>
In typical C ++ implementations, this program will not crash, but it will print 0 1 2 3 4 6 , and not 0 1 2 3 6 , as possible, because erasing the first 4 invalid p is by moving it along the second 4 .
Your C ++ implementation may have a special "debugging" mode in which this program will work at startup. For example, with GCC 4.8:
$ g++ -std=c++11 -W -Wall test.cc && ./a.out 0 1 2 3 4 6
but
$ g++ -std=c++11 -W -Wall -D_GLIBCXX_DEBUG test.cc && ./a.out /usr/include/c++/4.8/debug/safe_iterator.h:307:error: attempt to increment a singular iterator. Objects involved in the operation: iterator "this" @ 0x0x7fff5d659470 { type = N11__gnu_debug14_Safe_iteratorIN9__gnu_cxx17__normal_iteratorIPiNSt9__cxx19986vectorIiSaIiEEEEENSt7__debug6vectorIiS6_EEEE (mutable iterator); state = singular; references sequence with type `NSt7__debug6vectorIiSaIiEEE' @ 0x0x7fff5d659470 } Aborted
Understand that the program provokes undefined behavior anyway. The fact is that the consequences of undefined behavior are more dramatic in debug mode.
source share