What std::vector does when it grows
You keep a reference to v[0], call push_back, and the reference now reads garbage. Here is what std::vector does when it runs out of room, drawn one element at a time, and the exact rules for which iterators survive.
01 A reference that goes bad on its own
This code compiles without a warning and often prints 10. It is still wrong, and under a sanitiser or a different allocator it prints junk or crashes.
Nothing touched first. What changed is where the vector keeps its elements. To see why, you need the two numbers every vector carries.
02 Size and capacity
A std::vector<T> is three pointers: the start of a heap block, the end of the elements in use, and the end of the block. size() is the gap between the first two; capacity() is the gap between the first and the last. The slots in between are raw memory with no objects in them yet.
- element
- raw spare slot
While size() < capacity(), push_back builds the new element in the next spare slot and moves end along by one. Nothing else moves, so existing references stay valid.
The interesting case is the one where there is no spare slot left.
03 What really happens when it is full
A block cannot be stretched in place: the bytes after it may hold another object. So the vector gets a bigger block, moves everything into it, and frees the old one. Watch the reference first from the listing above while that happens.
- just constructed
- being moved from
- spare slot
- not allocated yet
- destroyed and freed
The vector holds 10, 20, 30, 40 in a block of 4 slots, so it is full. int& first = v[0]; is a reference straight into slot 0 of that block. The bigger block does not exist yet.
For a type like int, the library typically copies the old elements in one bulk memmove-style copy rather than one at a time. For class types it calls a constructor per element. Either way the old addresses are gone at the end.
04 Watch the capacity jump
Print capacity() each time data() changes, which is each time the vector moved to a new block.
That is a real run with Apple clang 17 and libc++ on macOS. 17 pushes caused 6 allocations, and the gaps double each time. GCC’s libstdc++ prints the same numbers. MSVC’s library grows by about 1.5 instead, so it allocates a little more often and wastes a little less. The standard only requires that push_back is amortised constant time, which any fixed factor above 1 gives you; the doubling argument is in How a growing array stays fast when it fills up.
05 Move or copy? It depends on noexcept
When the elements are class types, the vector has to decide how to bring each one across. Moving is cheaper, but if a move throws halfway, some elements are already gutted and the old block is no longer intact. push_back promises that if it throws, the vector is unchanged (the strong guarantee). So the library moves only when the move constructor is marked noexcept; otherwise it copies, if it can.
struct Plain {Plain() = default;Plain(const Plain&) { std::puts("copy"); }Plain(Plain&&) { std::puts("move"); }};std::vector<Plain> a(2);a.emplace_back();// prints: copy// copy
struct Safe {Safe() = default;Safe(const Safe&) { std::puts("copy"); }Safe(Safe&&) noexcept { std::puts("move"); }};std::vector<Safe> b(2);b.emplace_back();// prints: move// move
Both outputs are real runs (clang 17, libc++). The two lines are the two old elements being brought across; the new element is built in place and prints nothing. A defaulted move constructor is noexcept when every member’s move is, so most types get this for free. It is the hand-written ones that lose it.
06 Which iterators survive
Every iterator, pointer and reference into a vector is only an address. The rule is simple: anything that reallocates invalidates all of them; anything that shifts elements invalidates the ones at or after the change.
| Call | If it reallocates | If it does not |
|---|---|---|
| push_back / emplace_back | everything | only end() |
| insert / emplace | everything | at or after the insert point |
| erase | never reallocates | at or after the first erased element |
| pop_back | never reallocates | the last element and end() |
| reserve(n) | everything (if n > capacity) | nothing (n ≤ capacity: no-op) |
| resize(n) | everything | removed elements and end() |
| clear | never reallocates | everything (capacity is kept) |
| shrink_to_fit | everything | nothing |
You can tell in advance whether a push_back will reallocate: it does exactly when size() == capacity() before the call.
07 reserve: pay for the block once
If you know roughly how many elements are coming, reserve(n) allocates one block of at least n slots up front. No element is created, size() stays the same, and the pushes that follow never reallocate until you pass n.
08 When it bites
Pushing into a vector while you walk it is the classic crash: the range-for loop holds iterators into the old block, and the first reallocation frees it under them.
for (int x : v)
if (x > 0) v.push_back(-x);Appending inside a range-forThe hidden iterators point into the block that push_back frees. Loop by index over the original size, or collect into a second vector and append after.Node* parent = &nodes[0];
nodes.push_back(child);
parent->kids++;Pointers between elements of one vectorStoring &nodes[i] breaks on the next reallocation. Store the index i instead, or use a container whose elements never move, such as std::deque (for push at the ends) or std::list.v.reserve(v.size() + 1);reserve(size() + 1) in a loopreserve is allowed to give you exactly what you ask for, so this can turn doubling into growth by one and make the loop quadratic. Reserve the final total once, before the loop.Widget(Widget&& o) { … }A move constructor without noexceptEvery reallocation copies instead of moves. For types holding big buffers this is a silent slowdown. Mark it noexcept when it cannot throw, or = default it.v.clear();
// capacity() unchangedExpecting clear to free memoryclear destroys the elements but keeps the block. Call shrink_to_fit() (a non-binding request) or swap with an empty vector if you really need the memory back.