Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki MarkupReallocation can occur when a member function modifies its container. Modifying member functions include {{reserve()}} and {{resize()}}, {{push_back()}}, {{pop_back()}}, {{erase()}}, {{clear()}}, {{insert()}}, and others. In addition, assignment operations and modifying algorithms can also cause reallocation. When a container reallocates its elements, their addresses change. Consequently, the values of existing iterators are invalidated \[[Kalev 99|AA. C++ References#Kalev 99]\]. Using invalid iterators yields undefined results.

In particular the following operations on containers invalidate any iterators over these containers:

...

This applies only to contiguous-memory iterators, in particular vector}}s, {{deque}}s and {{string}}s. The {{swap() method of {{string}}s also invalidates iterators.

In general iterators on node-based containers such as {{list}}s are not invalidated via modification of the container, unless the element referenced by the iterator is itself erased.

Pointers and references to objects within a container are also invalidated when iterators are invalidated. A single exception applies for the deque class: it preserves pointers and references to internal objects upon inserts to either its beginning or its end, but it does not preserve iterators.

Wiki Markup
Consequently, the values of existing iterators may be invalidated \[[Kalev 99|AA. C++ References#Kalev 99]\]. Using invalid iterators yields undefined results.

Non-Compliant Code Example

...