Versions Compared

Key

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

Wiki Markup
Reallocation 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:

  • swap() on string
  • reserve() and resize(), push_back(), pop_back(), erase(), clear(), insert(), and others on contiguous-memory containers: vector, deque, and string

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.

Non-Compliant Code Example

...

Wiki Markup
\[[Meyers 01|AA. C++ References#Meyers 01]\] Item 43: Prefer algorithm calls to hand-written loops.
Wiki Markup

\[[Sutter 04|AA. C++ References#Sutter 04]\] Item 84: Prefer algorithm calls to handwritten loops.
Wiki Markup

\[[Kalev 99|AA. C++ References#Kalev 99]\] ANSI/ISO C+\+ Professional Programmer's Handbook.
Wiki Markup

\[[ISO/IEC 14882-2003|AA. C++ References#ISO/IEC 14882-2003]\] Section 24: Iterators Library.

...