In C++, what do std::vector's reserve, resize and shrink_to_fit each change, and when does reserving before a loop pay off?
answer
- capacity vs size vs a request
- reserved slots hold no objects
- one allocation instead of many
- reserve(size() + 1) in a loop
basics
~20 sreserve(n) raises capacity to at least n without creating elements; resize(n) changes size, constructing or destroying elements; shrink_to_fit asks, without obligation, to drop unused capacity. Reserve before a loop whose final count you know, so the loop never reallocates.
solid answer
~50 s`reserve(n)` changes only capacity: if n exceeds `capacity()` it reallocates once to at least n, and `size()` stays the same, so the new slots hold no objects and writing `v[i]` into them is undefined behaviour; you still `push_back`. A smaller n does nothing, because reserve never shrinks. `resize(n)` changes `size()`: growing value-initializes new elements (or copies a given value), shrinking destroys the tail. `shrink_to_fit()` is a non-binding request to cut capacity down to size. Reserving pays off when you know or can bound the final count, such as a 5,000-particle burst: one allocation replaces more than a dozen reallocate-and-transfer steps, nothing moves during the loop, and doubling does not overshoot. The trap is `reserve(size() + 1)` inside the loop: libc++ and libstdc++ allocate exactly what you ask for, so every iteration reallocates and the loop turns quadratic.
code
cpp · 26 lines#include <cstdio>
#include <vector>
struct Particle { float x, y, vx, vy; };
int main() {
std::vector<Particle> burst;
burst.reserve(1000); // capacity >= 1000, size still 0
std::printf("reserve: size=%zu capacity=%zu\n", burst.size(), burst.capacity());
std::vector<Particle> grid;
grid.resize(1000); // 1000 value-initialized particles
std::printf("resize: size=%zu capacity=%zu\n", grid.size(), grid.capacity());
const std::size_t reserved = burst.capacity();
for (int i = 0; i < 1000; ++i) burst.push_back({0.f, 0.f, 1.f, 1.f});
std::printf("capacity unchanged by the loop: %s\n",
burst.capacity() == reserved ? "true" : "false");
burst.push_back({}); // the 1001st element exceeds capacity
std::printf("after 1001st: size=%zu capacity=%zu\n", burst.size(), burst.capacity());
burst.resize(10);
burst.shrink_to_fit(); // non-binding request
std::printf("resize(10) + shrink_to_fit: size=%zu capacity=%zu\n", burst.size(), burst.capacity());
}go deeper
State that reserve changes capacity only, resize changes size, and shrink_to_fit is a request; and never index into reserved but unconstructed slots.
Explain the cost reserve removes: repeated allocate-transfer-free steps during growth. Show the reserve-then-push_back pattern and why reserve(size() + 1) in a loop is quadratic.
Use reserve as a latency tool: pre-size per-frame or per-request buffers from a known budget, keep their capacity across iterations, and shrink only after one-off spikes.
Decide where pre-sizing belongs in a codebase's guidelines: budgets declared per subsystem, sanitizer builds that catch reserve-and-index misuse, and when held capacity is an acceptable memory cost.
## Three functions, three different targets The three members look alike but change different things: | Call | Changes `size()` | Changes `capacity()` | Creates or destroys elements | |---|---|---|---| | `reserve(n)` | never | grows to at least n when n > `capacity()`; otherwise nothing | no | | `resize(n)` | sets it to n | grows if n > `capacity()` | constructs or destroys the difference | | `shrink_to_fit()` | never | may shrink toward `size()` | no | Two rules from the standard are worth quoting from memory. After `reserve(n)`, capacity is at least n if a reallocation happened and unchanged otherwise, and **no reallocation takes place during later insertions until the size would exceed that capacity**. And `shrink_to_fit` is a **non-binding request**: an implementation may ignore it. ## The classic reserve mistake Because `reserve` creates no objects, the reserved slots are not part of the vector: ```cpp std::vector<int> ids; ids.reserve(8); ids[3] = 42; // undefined behaviour: size() is still 0 ``` Nothing stops this at compile time, and a plain build usually appears to work. With libc++ built under `-fsanitize=address`, the write is reported as a `container-overflow`, because libc++ marks the unused capacity as poisoned. The fix is either `resize(8)` followed by indexing, or `reserve(8)` followed by `push_back` / `emplace_back`. ## When reserving pays off Without `reserve`, appending n elements one at a time costs about log2(n) reallocations on a doubling library, each of which allocates, transfers every element and frees the old block. Reserving up front changes that in three ways: 1. **One allocation instead of many.** For a 5,000-particle burst, a doubling library would otherwise reallocate fourteen times. 2. **Stable storage during the loop.** No element moves while you append, so pointers taken during the loop stay valid until the size passes the reserved capacity. 3. **No overshoot.** Doubling can leave up to half the block unused; reserving the exact count does not. It pays when the count is known or boundable: the size of a source range you are transforming, the particle budget for an effect, the number of rows a query returned. It does not pay when you have no idea of the count; guessing high wastes memory, and guessing low still reallocates. ## The quadratic anti-pattern ```cpp for (const Spawn& s : spawns) { particles.reserve(particles.size() + 1); // defeats geometric growth particles.push_back(make_particle(s)); } ``` The standard lets `reserve(n)` allocate more than n, but libc++ and libstdc++ both allocate exactly n. Each iteration therefore reallocates and transfers the whole vector: in a test run with libc++, 1,000 appends caused 1,000 reallocations, against 11 for plain `push_back`. Reserve **once, before the loop**, with the final count, or not at all. ## shrink_to_fit is only a request - libc++ implements it by reallocating to `size()` when the two differ. - libstdc++ does the same in normal builds, but its implementation does nothing when exceptions are disabled, or when the element type is neither copy-constructible nor nothrow-move-constructible. - The traditional alternative is to swap with a temporary. `std::vector<Particle>(particles).swap(particles);` copies into a fresh vector, which libc++ and libstdc++ allocate at exactly `size()`; `std::vector<Particle>().swap(particles);` releases the buffer entirely, and that one is guaranteed, because `swap` exchanges contents and capacity. Shrinking is worth it after a one-off spike, such as a level-load buffer that will not grow again. It is wasteful in a per-frame loop, where the next frame grows the buffer straight back. ## Choosing the figure to reserve - **From the source**: when transforming one range into another, `out.reserve(in.size())` is exact. - **From a budget**: an effect that may spawn at most 5,000 particles reserves 5,000 once, at load time rather than mid-frame. - **From history**: a per-frame scratch buffer that is cleared rather than destroyed keeps last frame's capacity, which acts as an automatic reserve. - **Not needed**: the constructor taking an iterator pair performs no reallocations when the iterators are forward iterators, because it can measure the distance first; only element-by-element appends need a manual `reserve`. ## resize versus reserve in practice - Use `resize(n)` when you will write elements by index, for example when filling a grid from several threads, each owning a range. - Use `reserve(n)` plus `push_back` / `emplace_back` when you append in order and want elements constructed only once, with their final values. - `resize(n)` on a type without a default constructor needs the `resize(n, value)` overload.
- Does std::vector::reserve ever reduce capacity, for example reserve(10) on a vector with capacity 1000?No. The standard says the capacity is unchanged when the argument is not greater than the current capacity, so `reserve` never shrinks and never invalidates anything in that case. To reduce capacity you need `shrink_to_fit()`, which is only a request, or a swap with a temporary vector; swapping with an empty temporary is guaranteed to release the buffer.
- What does std::vector::reserve throw when the requested capacity is too large?It throws `std::length_error` when n exceeds `max_size()`. Below that limit, the allocation itself can still fail, and with the default allocator that surfaces as `std::bad_alloc`. If an exception is thrown, other than by the move constructor of a type that cannot be copied, `reserve` has no effect on the vector.
- After reserve(n) you can assign v[0] through v[n-1] directly
- reserve(n) creates n default-constructed elements, just like resize(n)
- Calling reserve(size() + 1) before each push_back is a good optimization
- shrink_to_fit() is guaranteed to reduce capacity to size()
- reserve with a smaller value shrinks the vector's buffer