Iterator Invalidation¶
1. Problem Statement¶
In C++, iterators, references, and pointers into containers are only valid under specific structural conditions. Container mutations can invalidate some or all of them.
Using an invalidated iterator/reference/pointer is undefined behavior.
This pitfall is common because APIs often look symmetric:
- obtain iterator,
- mutate container,
- keep using iterator.
The sequence compiles, may appear to work, and then fails under different capacity/layout/runtime conditions.
2. Scope and Non-Goals¶
2.1 Scope¶
This article covers:
- why invalidation happens,
- typical invalidation patterns per container family,
- safe mutation/iteration strategies,
- review and migration checklists.
2.2 Non-Goals¶
We do not reproduce the full standard table verbatim. Focus is practical engineering reasoning with high-frequency cases.
3. Minimal Example¶
#include <vector>
std::vector<int> v{1, 2, 3};
auto it = v.begin();
v.push_back(4); // may reallocate
int x = *it; // UB if reallocation occurred
If push_back triggers reallocation,
all old iterators/references/pointers into v become invalid.
4. Why Invalidation Happens¶
Containers manage internal storage and topology. Mutating operations may:
- move elements to new memory,
- shift positions,
- erase nodes,
- change internal structure.
Any handle that assumed old storage/topology can become stale.
5. Handle Types: Different Names, Similar Risk¶
For many containers, invalidation affects not only iterators, but also:
- references to elements,
- pointers to elements,
- views/span-like adapters derived from old data.
Do not audit only iterators and ignore references/pointers.
6. Container Families and Typical Behavior¶
6.1 Contiguous Containers (vector, string)¶
Risk profile:
- reallocation can invalidate all iterators/references/pointers,
- insertion/erase can invalidate ranges at/after affected position,
reserve/capacity planning changes risk profile but does not remove it globally.
6.2 deque¶
Has segmented storage; invalidation rules are nuanced. Some operations invalidate all iterators but preserve references in specific cases, others invalidate local ranges.
Assume complexity unless operation-specific behavior is known.
6.3 Node-Based Containers (list, forward_list)¶
Insertion often keeps existing iterators stable. Erasing a node invalidates iterators/references to erased node only.
Better iterator stability, but different performance trade-offs.
6.4 Associative/Unordered Containers¶
map/set (tree-based) generally provide strong iterator stability except erased elements.
unordered_* may invalidate iterators on rehash.
References/pointers to elements often have different guarantees than iterators.
7. Classic Failure Patterns¶
7.1 Mutate While Iterating with Cached End¶
Caching end in mutating loop is often wrong for invalidation-sensitive containers.
7.2 Erase in Loop with Incorrect Increment¶
for (auto it = v.begin(); it != v.end(); ++it) {
if (pred(*it)) {
v.erase(it); // it invalidated; ++it afterwards is UB
}
}
Correct pattern uses returned iterator from erase.
7.3 Store Pointer to vector Element Across Growth¶
8. Correct Erase-Loop Pattern¶
for (auto it = v.begin(); it != v.end(); ) {
if (pred(*it)) {
it = v.erase(it); // returns next valid iterator
} else {
++it;
}
}
This pattern is fundamental and should be standardized in team code style.
9. Capacity Planning Is Helpful, Not Absolute¶
vector::reserve can reduce reallocations:
But it does not make all iterators universally stable. Operations like erase/insert at positions still have local invalidation effects.
Treat reserve as optimization tool, not correctness proof.
10. Reacquire After Potentially Invalidating Operations¶
General safe rule:
- after mutation that may invalidate handles,
- reacquire iterators/references from container state.
Do not assume old handles remain valid by coincidence.
11. Index-Based Traversal Trade-Off¶
For contiguous containers, index-based loops can sometimes avoid iterator invalidation pitfalls:
Still requires clear mutation policy (size growth, erase shifts).
Not universally safer by default.
12. erase-remove Idiom¶
For removing elements by predicate in sequence containers:
This centralizes mutation and reduces manual iterator mistakes.
In C++20+, prefer std::erase_if(v, pred) where available.
13. Range-Based for and Mutation¶
Mutating container structure inside range-based loop over same container is often unsafe.
Avoid unless operation semantics are explicitly known to preserve required handles.
14. Unordered Containers and Rehash Surprises¶
unordered_map / unordered_set can rehash when bucket count changes.
Rehash can invalidate iterators broadly.
Mitigations:
- reserve bucket count in advance,
- avoid long-lived iterators across insert-heavy phases,
- reacquire iterators after operations that may trigger rehash.
15. Borrowed Views Are Also at Risk¶
If code builds std::span, string_view, or custom views from container storage,
container mutation can invalidate those views too.
Iterator-invalidation discipline should include all borrowed handles, not just STL iterators.
16. Concurrency Amplifies the Problem¶
Concurrent mutation and iteration without proper synchronization can cause:
- data races,
- stale/dangling handles,
- container invariants violations.
Thread safety and invalidation safety are related but distinct requirements. You need both.
17. Performance vs Stability Trade-Off¶
Node-based containers offer stronger iterator stability, but may have worse cache locality and higher allocation overhead.
Contiguous containers offer great locality, but weaker handle stability during structural mutations.
Choose container based on access/mutation pattern, not habit.
18. API Design Guidance¶
If API returns iterators/references into internal containers, document invalidation conditions explicitly.
Better yet, where possible:
- expose value snapshots,
- expose stable IDs/handles managed by owner,
- minimize external dependence on internal iterator stability.
19. Typical Anti-Patterns¶
- Storing iterators as long-lived object members without mutation protocol.
- Keeping pointers into vector/string across growth operations.
- Mutating same container inside callback invoked during iteration.
- Assuming all standard containers have similar invalidation semantics.
- Treating successful tests as proof of validity.
20. Safer Mutation Patterns¶
- Phase separation: collect changes first, apply mutations later.
- Recompute handles after mutation.
- Use return iterator from mutating operations (
erase,insertwhere applicable). - Keep mutation scope narrow and local.
These patterns reduce cognitive load and bug surface.
21. Legacy Code Migration Strategy¶
- Search for long-lived iterator/reference fields.
- Audit loops that mutate during iteration.
- Replace fragile loops with canonical erase/update patterns.
- Introduce container-specific helper utilities.
- Add regression tests for growth/rehash-heavy scenarios.
22. Tooling Support¶
Use sanitizers and debug iterators (where library/toolchain supports them):
- ASan/UBSan for runtime UB symptoms,
- debug iterator modes in STL implementations,
- static analysis for suspicious mutation-after-capture patterns.
Tooling does not replace semantic understanding, but catches many high-risk cases early.
23. Review Checklist¶
- [ ] Does code keep iterators/references/pointers across container mutation?
- [ ] Are container-specific invalidation rules known for each operation?
- [ ] Are erase loops using returned iterator pattern?
- [ ] Are views/spans/string_views derived from mutable container storage?
- [ ] Could reserve/rehash behavior invalidate assumptions?
- [ ] Is mutation and iteration protocol documented?
If any answer is uncertain, refactor for clearer safety.
24. Mitigation Summary¶
- Learn invalidation rules per container and operation.
- Reacquire handles after potentially invalidating mutations.
- Prefer canonical loop patterns for erase/update.
- Select container by required stability profile.
- Make lifetime/invalidation assumptions explicit in API contracts.
Example¶
A runnable version of this topic:
25. Conclusion¶
Iterator invalidation is not an edge case; it is a central correctness property of container usage.
Robust C++ code treats iterator/reference/pointer validity as a contract, updated whenever container structure changes.
Once teams internalize this model, an entire class of undefined behavior bugs becomes preventable through routine review discipline.