skip to content

In C++, what do a lambda's [=] and [&] capture defaults capture, and at what moment is each value taken?

level: juniorimportance: must knowfreq 80%

answer

  1. only what the body uses
  2. copy taken at creation, not at call
  3. a reference sees later writes
  4. globals and statics are never captured

basics

~20 s

[=] copies each local variable the lambda body uses into the closure when the lambda expression is evaluated; [&] makes the body refer to those variables instead. Globals and static variables are never captured, so the body reads their current values.

solid answer

~40 s

A lambda's capture list decides how the enclosing function's local variables reach its body. `[=]` captures **by copy**: each automatic variable the body uses becomes a data member of the closure, initialized when the lambda expression is evaluated, so later changes to the original are invisible. `[&]` captures **by reference**: the body reads and writes the originals, sees every later change, and depends on them still being alive when it runs. Neither default captures a variable the body does not use. Globals, namespace-scope variables and `static` locals are never captured at all; the body reads their current value. Defaults combine with explicit captures, as in `[=, &total]` or `[&, id]`, and many teams prefer a fully explicit list such as `[id, &log]` so each capture's mode is visible in review.

code

cpp · 18 lines
cpp
#include <cstdio>

int g_clicks = 0;  // namespace scope: never captured

int main() {
  int volume = 1;
  int total = 0;
  static int session = 7;  // static storage duration: never captured
  auto by_copy = [=] { return volume; };  // copies volume now
  auto by_ref = [&] { return volume; };   // refers to volume
  auto mixed = [volume, &total] { return volume + total; };  // explicit list
  auto no_capture = [] { return session + g_clicks; };       // nothing to capture
  volume = 5;
  total = 100;
  session = 9;
  g_clicks = 1000;
  std::printf("%d %d %d %d\n", by_copy(), by_ref(), mixed(), no_capture());
}

go deeper

for a junior

Know that [=] copies and [&] refers, that only variables the body uses are captured, and that the copy is taken when the lambda is created, not when it runs.

for a middle

Explain the closure members behind by-copy captures, why statics and globals need no capture, and the rules for mixing a default with explicit captures such as [=, &total].

for a senior

Argue for explicit capture lists in code review: they expose accidental reference captures in deferred callbacks, large hidden copies and the implicit this capture of [=].

for a principal

Frame capture style as a team rule: when defaults are acceptable for short local algorithms and when stored or asynchronous lambdas must list every capture explicitly.

## What a capture list does A **lambda expression** creates a **closure object**: an object of an unnamed class whose call operator runs the lambda's body. The body cannot simply use any variable in sight. A variable with **automatic storage duration** (an ordinary local or a parameter) and the object `*this` are what the standard calls **local entities**, and the body may use one only if the lambda **captures** it. The capture list between the square brackets says which local entities are captured and how. Variables with **static storage duration** are different: globals, namespace-scope variables and `static` locals are not local entities. A lambda never captures them; its body names them directly, exactly as an ordinary function would, and always sees their current value. ## The two capture defaults | Capture list | What it captures | When the value is fixed | What a later call sees | |---|---|---|---| | `[]` | nothing | not applicable | parameters, globals and statics only | | `[=]` | by copy, each local variable the body uses | when the lambda expression is evaluated | the value at creation | | `[&]` | by reference, each local variable the body uses | never: no copy is made | the current value, while the variable lives | A default captures **implicitly**: only the local variables the body actually uses are captured, so `[=]` does not copy the whole stack frame. For each variable captured by copy, the closure type gets an unnamed non-static data member, initialized when the lambda expression is evaluated. For a variable captured by reference, it is unspecified whether the closure stores anything at all; what matters is that the body refers to the original. "Uses" has a precise meaning. A variable that appears only in an **unevaluated operand**, such as `sizeof(n)`, is not captured; a `const int limit = 10;` read only for its value is not **odr-used**, so even a lambda with an empty capture list may read it. Compiled with Apple clang 21, a `[=] { return sizeof(n); }` closure had a size of 1 byte, which shows that `n` was never copied in. ## Watching the timing The code example builds four lambdas, changes every variable, then calls them. It prints `1 5 101 1009`: 1. `by_copy` used `[=]`, so its member was initialized with `volume` while `volume` was still 1. The later assignment of 5 does not reach it. 2. `by_ref` used `[&]`, so its body reads `volume` itself and sees 5. 3. `mixed` lists its captures explicitly: `volume` by copy (still 1) and `total` by reference (now 100). 4. `no_capture` has an empty capture list, yet it reads `session` and `g_clicks`, because a `static` local and a global need no capture. It sees their new values, 9 and 1000. ## Mixing a default with explicit captures - `[=, &total]` copies everything the body uses except `total`, which it captures by reference. - `[&, id]` refers to everything except `id`, which it copies. - After a `&` default, an explicit capture may not also say `&`: `[&, &count]` is ill-formed. After a `=` default, an explicit by-copy capture such as `[=, id]` is ill-formed, because the default already copies. - A name may appear only once in the list, so `[id, id]` is rejected. - A fully explicit list, `[id, &log]`, is the most reviewable form: a reader sees every captured name and its mode without scanning the body. ## Mistakes interviewers listen for - Believing `[=]` copies every local in scope. It copies only what the body uses. - Believing a by-copy capture reads the variable when the lambda is **called**. The copy is taken when the lambda is **created**. - Believing `[&]` keeps the referenced variables alive. It does not: a by-reference capture of a local that has gone out of scope dangles. - Believing a global must be captured, or expecting a `[=]` lambda to hold a snapshot of a global. Globals are read live. - Believing `[=]` inside a member function copies the data members. It captures the `this` pointer instead, which the separate question on capturing `this` covers. ## How to answer Say that `[=]` copies and `[&]` refers, that both apply only to the automatic variables the body uses, and that the copy happens when the lambda expression is evaluated. Add that statics and globals are never captured, then mention the explicit-list style and why reviewers like it.

  • How do you capture one variable by reference and everything else by copy?
    Combine the default with an explicit capture: `[=, &total]` copies every local the body uses except `total`, which it captures by reference. The reverse is `[&, id]`. The explicit capture must use the other mode: `[=, id]` and `[&, &id]` are both ill-formed because they repeat what the default already does.
  • Why do many C++ style guides prefer explicit capture lists over [=] and [&]?
    An explicit list such as `[id, &log]` shows every captured name and its mode at the point of creation. With a default, a reviewer must read the whole body to know what is captured, an edit to the body can silently add a capture, a large object can be copied without anyone noticing, and inside a member function `[=]` quietly captures `this` rather than copying members.

A by-copy capture is a photograph taken when the lambda is created: later changes to the scene do not alter the photo. A by-reference capture is a window onto the live scene, and it shows nothing useful once the scene is gone.

  • [=] copies every local variable in scope, whether the body uses it or not.
  • A by-copy capture reads the variable's value each time the lambda is called.
  • A global variable must be captured before a lambda body can use it.
  • [&] keeps the captured local variables alive for as long as the lambda exists.
  • Inside a member function, [=] copies the object's data members into the closure.