Topic 19 of 27 · Advanced
How can vector growth invalidate a perfectly valid pointer?
When vector capacity is exhausted, it allocates a new buffer and moves or copies elements there. References, pointers and iterators into the old buffer become invalid.
C++20; compile with g++ -std=c++20.
Detailed answer
When vector capacity is exhausted, it allocates a new buffer and moves or copies elements there. References, pointers and iterators into the old buffer become invalid.
reserve can prevent reallocations until capacity is exceeded, but it does not change size. Erasing elements invalidates positions at or after the erase point even without reallocation.
Choose stable handles, indices with version checks, or a container with the needed invalidation contract. Do not store raw element pointers across mutations without proving stability.
Internal working
Contiguous storage is vector's core contract. Capacity growth factors are implementation-dependent; amortized constant append does not mean each append is constant-time.
Practical scenario
A registry stores pointers into a vector of users. Adding a new user reallocates the vector and later callbacks dereference freed storage.
#include <vector>
#include <iostream>
int main(){std::vector<int> v;v.reserve(4);v.push_back(7);std::cout<<v.size()<<" "<<v.capacity()<<"\n";}Common mistakes
- Treating reserve as resize.
- Assuming all iterators survive erase.
Key takeaways
- Check mutation contracts.
- Amortized cost allows expensive operations.
- Separate handle stability from lookup speed.
Follow-up challenges
- How does deque invalidation differ?
- Would list improve the actual access pattern?