skip to content

When a C++ program builds a std::string URL from many segments, why prefer += and reserve over url = url + segment?

level: middleimportance: should knowfreq 45%

answer

  1. which operator+ overload runs
  2. a new string every pass
  3. append in place
  4. reserve: one allocation
  5. C++20: reserve never shrinks

basics

~20 s

url = url + segment builds a new string each pass, copying everything so far: quadratic work and an allocation per pass. url += segment appends in place into spare capacity, and reserve(total) turns the whole build into one allocation.

solid answer

~40 s

`url + segment` calls `operator+(const std::string&, const std::string&)`, which is specified as copy `lhs`, append `rhs`, return the result. In a loop that copies the whole URL so far on every pass, so total work is quadratic and every pass allocates. `url += segment` calls `append`, which writes into spare capacity and reallocates only when the capacity runs out; libc++ and libstdc++ grow geometrically, so appends are cheap on average. `reserve(n)` reallocates only if `capacity()` is below `n` and leaves `capacity() >= n`; computing the final length first makes the whole build one allocation. In one measured run of 1,000 segments with libc++, the `url = url + ...` loop made 1,999 allocations, `+=` made 11, and `reserve` then `+=` made 1. Since C++20 `reserve` never shrinks, and C++26 removes the no-argument `reserve()`.

code

cpp · 21 lines
cpp
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> segments = {"api", "v1", "players", "42", "inventory"};

    std::string url = "https://example.com";
    std::size_t total = url.size();
    for (const auto& s : segments) total += 1 + s.size();
    url.reserve(total);                         // one allocation up front

    const char* before = url.data();
    for (const auto& s : segments) {
        url += '/';
        url += s;                               // appends in place, no new buffer
    }
    std::cout << url << '\n';
    std::cout << std::boolalpha << "same buffer: " << (url.data() == before)
              << ", capacity >= size: " << (url.capacity() >= url.size()) << '\n';
}

go deeper

for a junior

Prefer += in loops and know that url = url + seg makes a new string every time.

for a middle

Explain the operator+ specification, geometric growth in real libraries, and exactly what reserve guarantees, including the C++20 no-shrink rule.

for a senior

Find these loops with an allocation profile or a counting allocator, and fix them with a computed reserve rather than guesses.

for a principal

Decide where text building is hot enough to warrant reserve discipline in review, and where clarity wins and one extra allocation is fine.

## Two spellings, two overloads `std::string` offers two ways to add text, and they are not equivalent: - `url += segment` calls `operator+=`, which is `append`. It **modifies `url` in place**: if `size() + segment.size()` fits in `capacity()`, the characters are written into existing spare space; otherwise the string allocates a larger buffer, copies its contents once, and continues. - `url = url + segment` calls `operator+(const std::string&, const std::string&)`. The standard specifies it as: make `r` a copy of `lhs`, `r.append(rhs)`, return `r`. So it **builds a new string** containing a full copy of `url`, then assigns it back. In a loop over `n` segments, the second spelling copies the first segment `n` times, the second `n - 1` times, and so on: **quadratic** total work, and at least one allocation per pass. That arithmetic is common to every language with mutable buffers; the C++-specific part is knowing which overload you called. ## Measured A counting `operator new` around three ways of appending 1,000 segments of 24 characters, compiled with Apple clang 21 and libc++ at `-O2`: | loop | allocations | |---|---| | `a = a + '/' + seg;` | 1,999 | | `b += '/'; b += seg;` | 11 | | `c.reserve(total);` then `+=` | 1 | The first loop allocates about twice per pass: once for the copy made by `a + '/'`, and once more when appending `seg` overflows that copy's tight capacity. The exact numbers are libc++'s; the shape is what matters. ## Why += stays cheap: geometric growth When `append` runs out of capacity, both major libraries grow the buffer by a factor rather than by the amount requested: libstdc++ doubles the old capacity when the request is smaller than that, and libc++ grows to the larger of the request and twice the current capacity. Geometric growth makes a long run of appends cost a constant amount per character on average. The factor is an implementation choice; the standard specifies what `append` does, not by how much the capacity grows. ## reserve, capacity and shrink_to_fit - `capacity()` returns the size of the allocated storage; `size() <= capacity()` always holds. - `reserve(n)` is a request for **at least** `n`: reallocation happens **if and only if** the current capacity is less than `n`, and afterwards `capacity() >= n`. - **C++20 changed `reserve`**: before C++20 a call with `n` below the capacity was a non-binding request to shrink; since C++20 it never shrinks. **C++26 removes** the no-argument `reserve()` overload, whose only job was that shrink request. - `shrink_to_fit()` is the explicit, still **non-binding**, request to drop excess capacity. Reserve when you know the final length, or a good upper bound, before you start: 1. sum the lengths of the base and every segment, plus separators; 2. call `url.reserve(total)` once; 3. append with `+=`; no further allocation and no pointer invalidation happens while the total holds. ## Chained + is not as bad as a loop A single expression such as `base + "/" + id + "/inventory"` is not quadratic. Since C++11 there are overloads of `operator+` taking an **rvalue** `std::string` on the left; they append into that temporary and return it moved. Only the first `+` copies `base`; each later `+` extends the same temporary, reallocating only when its capacity runs out. The problem is specifically the loop that copies the accumulated string on every pass. ## Other building operations and their costs - `append(n, c)` and `+= c` add characters at the end, the cheap direction. - `insert(0, text)` or `text + url` places characters in front, which shifts or copies everything already there, so building a string backwards costs linear time per step. - `resize_and_overwrite` (C++23) lets a C-style function write directly into the string's buffer without first zero-filling it, for the rare case where that initialisation shows up in a profile. - Formatting the whole URL in one call is the subject of the material on `std::format`. ## Interview-ready summary - `+=` and `append` mutate in place; `x = x + y` creates a new string each time. - Geometric growth keeps `+=` amortized cheap in real libraries; `reserve` removes even those reallocations. - `reserve` never shrinks since C++20; use `shrink_to_fit` to ask for that. - Any reallocation invalidates pointers from `c_str()` taken earlier, so finish building before handing the pointer out.

  • Does reserve(10) on a string whose capacity is 100 release memory?
    Not since C++20. `reserve` reallocates only when the current capacity is below the argument, so `reserve(10)` leaves the capacity at 100. Before C++20 it was a non-binding shrink request that some libraries honoured. To ask for memory back, call `shrink_to_fit()`, which is still non-binding.
  • Why is base + "/" + id not quadratic even though each + returns a new string?
    Since C++11 `operator+` has overloads taking an rvalue `std::string` as the left operand. The first `+` copies `base` into a temporary; each later `+` receives that temporary as an rvalue, appends to it and returns it moved, so the characters are copied once more only when the temporary's capacity runs out.

  • url = url + seg and url += seg compile to the same in-place append.
  • reserve(n) sets the capacity to exactly n characters.
  • Calling reserve with a smaller value shrinks the buffer in C++20.
  • The standard requires std::string to double its capacity when it grows.
  • Any chain of + in one expression is quadratic in the number of pieces.

Assumes C++20 or later: reserve never shrinks since C++20, and C++26 removes the no-argument reserve().