Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Lambda capture by reference: `[&]`

`[&]` sets the by-reference capture default: the lambda uses the original local objects rather than copies, but it does not keep those objects alive.

Version: ISO C++23; implementation support may vary

Syntax

[&](parameters) { body }
[&x](parameters) { body }
[&, x](parameters) { body }
[=, &x](parameters) { body }

The term lambda capture by reference ([&]) refers here to a lambda's by-reference capture default. It implicitly captures eligible variables of automatic storage duration from enclosing scopes when their use calls for capture, not every variable in scope. [&x] explicitly captures only x by reference; [&, x] captures x by copy, and [=, &x] captures x by reference with a by-copy default. [&, &x] is ill-formed. A visible global such as ::offset needs no capture. [&] dates to C++11; the rules described here apply to C++23.

When two nested lambdas capture total by reference, both refer to the same object. If the outer lambda captured total by copy instead, the inner lambda's reference would refer to the copy in the outer closure. Changing only the capture would make total += amount ill-formed: the outer lambda is not mutable, so the copy is treated as const. You do not need mutable to change a non-const object captured by reference, and mutable cannot remove the object's const qualification. Neither capturing an object by reference nor copying a closure that captures it by reference extends the object's lifetime. Before returning or storing a lambda, make sure the object will still be alive when the lambda uses it; accessing it through a dangling reference is undefined behavior. If you capture a reference variable by reference, it is the lifetime of the object it refers to that matters.

In R& result, & declares an lvalue reference, not a capture. result = f() assigns to the caller's object; it does not rebind the reference. A parameter such as const int& amount does not let you modify the argument through that reference.

Examples

#include <iostream>

int offset = 2;

template<class F, class R>
void record(F&& f, R& result) {
    result = f();
}

int main() {
    int total = 1;
    int result = 0;
    const int step = 3;

    record([&] {
        auto add = [&](const int& amount) { total += amount; };
        add(step);
        return total + ::offset;
    }, result);

    std::cout << total << ' ' << result << '\n';
}

Result

4 6

`add(step)` changes `total` from `1` to `4`. The outer lambda returns `4 + ::offset`, and `record` writes `6` through `result`. Both lambdas run while the objects they use are alive. The expected output line is `4 6`.

Related lessons

  • C++ · Lesson 15 · Advanced · Version: 3
  • C++ · Lesson 24 · Advanced · Version: 3

Sources