Skip to content

What std::vector does when it grows

Working knowledgeUnder the hood

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.

dangle.cpp
#include <cstdio>
#include <vector>
int main() {
std::vector<int> v = {10, 20, 30, 40};
int& first = v[0];
v.push_back(50); // may move every element
std::printf("%d\n", first); // undefined behaviour
}

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.

size 3, capacity 4: one push_back fits without moving anything
One heap block of 4 slots
begin100
201
302
end3
  • 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.

push_back into a full vector
Step 1 of 9
capacity 4first refers to old slot 0
Old block · capacity 4
first100
201
302
403
New block · capacity 8
0
1
2
3
4
5
6
7
  • 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.

4 size

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.

grow.cpp
#include <cstdio>
#include <vector>
int main() {
std::vector<int> v;
const int* last = nullptr;
for (int i = 1; i <= 17; ++i) {
v.push_back(i);
if (v.data() != last) {
std::printf("size %2zu capacity %2zu new block\n",
v.size(), v.capacity());
last = v.data();
}
}
}
Shell
$ clang++ -std=c++20 grow.cpp -o grow && ./grow
size 1 capacity 1 new block
size 2 capacity 2 new block
size 3 capacity 4 new block
size 5 capacity 8 new block
size 9 capacity 16 new block
size 17 capacity 32 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.

Move may throw
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
Move is noexcept
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.

What each call invalidates (C++ standard rules)
CallIf it reallocatesIf it does not
push_back / emplace_backeverythingonly end()
insert / emplaceeverythingat or after the insert point
erasenever reallocatesat or after the first erased element
pop_backnever reallocatesthe last element and end()
reserve(n)everything (if n > capacity)nothing (n ≤ capacity: no-op)
resize(n)everythingremoved elements and end()
clearnever reallocateseverything (capacity is kept)
shrink_to_fiteverythingnothing

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.

C++
std::vector<int> v;
v.reserve(1000); // one allocation
for (int i = 0; i < 1000; ++i)
v.push_back(i); // never moves
1,000 push_backs, no reserve11 allocationsWith doubling from 1: capacities 1, 2, 4 … 1024. Each move copies everything stored so far, about 1,000 element moves in total.
reserve(1000) first1 allocationOne block, no moves, and references taken during the loop stay valid.

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.

09 Check yourself

Question

v has size() == 3 and capacity() == 4. You take int* p = &v[1]; and call v.push_back(9);. Is p still valid?

Question

A type has a copy constructor and a move constructor that is not noexcept. What does a reallocating push_back do with the old elements?

Question

Why is v.push_back(v[0]) safe even when it reallocates?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?