Invalidation
From Cppwiki
Invalidation refers to the state of an iterator, pointer, or reference to an object whose lifetime has ended; or to an iterator or pointer that has not been initialized. Any use of the value of an invalid object elicits undefined behaviour.
Contents |
Standard library containers
Erasing an element from any container will invalidate any iterators, pointers, or references to that element. (Note: Special care must be taken when attempting to erase in a loop.)
Most standard containers model some sort of directed acyclic graph whose nodes remain valid until you erase them. deque, string, and vector model random-access sequences (arrays) and will invalidate in additional cases, described below.
deque
- Every insertion will invalidate all iterators. Insertion elsewhere than the front or back will invalidate all pointers and references as well.
- Erasure that results in an empty deque, or that removes any element besides those at the front and back, will invalidate all iterators, pointers, and references.
vector
- Insertion with sufficient capacity() will invalidate only those iterators, pointers, and references to elements following the point of insertion. Otherwise, all of them are invalidated.
- Erasure will invalidate iterators, pointers, and references to elements following the point of insertion.
string
Although string is superficially similar to vector, Standard C++ allows it to use techniques such as non-contiguous storage and copy-on-write (where all copies of a string share the same internal representation). To remain portable, C++ users should treat as invalid all iterators, pointers, and references into a string having undergone any of these operations:
- the first call of non-const operator[](), at(), begin(), rbegin(), end(), or rend() after being copied, or after forming a copy of another string
- any other non-const member function of any string
- The data() and c_str() members (which may force a contiguous reallocation of a non-contiguous string)