Lambda Expressions#

Summary based on C++ Primer, 5th ed. Chapter 10.3 and Chapter 14.8.1.

1. Syntax and Under-the-Hood Mechanism#

[CAPTURE_LIST](PARAMETER_LIST) mutable -> RETURN_TYPE { /* FUNCTION_BODY */ }
  • While PARAMETER_LIST, mutable, and -> RETURN_TYPE are optional, the capture list [] and function body {} are always required.
  • Under-the-Hood Mechanism:
    • A lambda expression is syntactic sugar for an unnamed Closure class and a temporary Closure object generated automatically by the compiler:
      1. Items in the capture list [CAPTURE_LIST] become data members of the unnamed class, initialized via the class’s constructor initializer list when the lambda is created.
      2. The parameter list (PARAMETER_LIST) and body { /* FUNCTION_BODY */ } become the class’s overloaded function-call operator operator().
      3. Crucially, operator() is generated as a const member function operator()(PARAMETER_LIST) const by default.
// Developer's lambda code
size_t v1 = 42;
auto f = [v1](size_t x) { return v1 + x; };

// Closure class generated by the compiler
class __Lambda {
private:
    size_t v1; // 1. Captured items become data members of the closure class
public:
    __Lambda(size_t v) : v1(v) {} // 2. Initialized at lambda creation time via initializer list

    // 3. The lambda body becomes a const member function operator() by default
    auto operator()(size_t x) const {
        return v1 + x;
    }
};
auto f = __Lambda(v1); // 'f' is an instance of this compiler-generated class

2. The Core Unified Principle: Two Steps Govern Every Capture & const Case#

Every capture rule in C++ follows a single 2-step principle:

The Unified Principle of Lambda Captures

  1. Step 1 — Capture [] Declares Data Members: The capture list simply determines what member types are declared inside the compiler-generated Closure class.
  2. Step 2 — Default operator()() const Applies Only Top-Level const: Without mutable, every data member receives Top-Level const only. Adding mutable removes only that Top-Level const, and can never strip away a member’s existing Low-Level const.

Whether capturing by value, by reference, or via this, there are zero exceptions:

Capture ItemStep 1: Member Generated in Closure ClassStep 2: Result of Top-Level const (without mutable)Mutability Summary
[v] (int v, value capture)int v;const int❌ Cannot modify copy
✅ Can modify copy with mutable
[p] (int* p, pointer by value)int* p;int* const❌ Cannot reassign p = ...
✅ Can modify pointee *p = 99
[&x] (int x, non-const ref)int& x;Still int&
(a reference is inherently Top-Level const)
✅ Can modify original x even without mutable
[&cx] (const int cx, const ref)const int& cx;const int&❌ Cannot modify original cx even with mutable because Low-Level const remains
[this] (inside non-const member fn of class S)S* const __this;S* const✅ Can modify original member even without mutable
[this] (inside const member fn of class S)const S* const __this;const S* const❌ Cannot modify original member even with mutable because Low-Level const remains
[*this] (C++17 object value copy of class S)S __this;const S❌ Cannot modify copy
✅ Can modify copy with mutable

3. Value Capture and Why mutable Is Needed#

  • Copied at Creation Time: As shown by the Closure class constructor __Lambda(v1) above, a value-captured variable is copied when the lambda is created, not when it is called.
  • Top-Level const and mutable:
    • Applying top-level const to size_t v1; produces const size_t, disallowing mutation inside operator()() const.
    • Adding mutable omits const from operator()(), allowing modification of the internal copied member without affecting the outer variable.
size_t v1 = 42;

// 1. Value capture: copies the value 42 at lambda creation time
auto f1 = [v1]() { return v1; };
v1 = 0;
auto a = f1(); // 42: internal member remains 42 even after outer v1 becomes 0

// 2. mutable: removes const from operator()() so the internal copy can be modified
// auto err = [v1]() { return ++v1; };      // ❌ Compile error: member v1 is const size_t inside operator()() const
auto f2 = [v1]() mutable { return ++v1; };  // ✅ Valid: increments internal copy from 42 -> 43 while outer v1 remains 0

4. Reference Capture constness and Dangling Reference Pitfalls#

  • Comparing [v], [&x], and [&cx] via the Generated __Lambda:
    • For int x, [&x] declares the member int& x;. Because a reference is inherently Top-Level const, applying Top-Level const leaves the referenced int non-const, so outer x can be mutated even when the lambda itself is declared const auto lam = ...; below.
    • Conversely, for const int cx, [&cx] declares const int& cx; with Low-Level const from the start, so even mutable cannot make it modifiable.
  • Dangling Reference Hazard: If a lambda outlives the local variable it captured by reference, such as when returning a lambda from a function or registering an asynchronous callback, the reference member points to destroyed stack memory, causing a Dangling Reference (UB).
int v = 10;
int x = 10;
const int cx = 10;

// Developer's lambda: even declared as const auto
const auto lam = [v, &x, &cx]() {
    // ++v;   // ❌ Compile error: value member int v becomes const int via Top-Level const
    ++x;      // ✅ Valid: even inside operator() const, int& x can mutate outer x (10 -> 11)
    // ++cx;  // ❌ Compile error: member itself has type const int& cx (Low-Level const, even mutable cannot fix)
};
lam();

// Closure class generated by the compiler
class __Lambda {
private:
    int v;          // [v]   : value copy member
    int& x;         // [&x]  : non-const reference member
    const int& cx;  // [&cx] : const reference member
public:
    __Lambda(int _v, int& _x, const int& _cx)
        : v(_v), x(_x), cx(_cx) {}

    void operator()() const { // type of this: const __Lambda* const
        // ++this->v;   // ❌ Compile error: this->v is const int
        ++this->x;      // ✅ Valid: this->x is still int& (referenced object is NOT const)
        // ++this->cx;  // ❌ Compile error: member itself is declared const int& (Low-Level const)
    }
};

// Bug example: Dangling Reference
auto make_bad_lambda() {
    int local = 10;
    return [&local]() { return local; }; // Captures local variable by reference that dies when function returns
}

5. Class Data Members and this Pointer Capture Pitfalls#

In C++, lambdas never capture class data members directly. Writing [DATAMEMBER] produces error: capture of non-variable. Whenever a lambda inside a member function accesses a member, the compiler captures the this pointer (S* const) instead.

  • The [=] Trap:
    • Writing [=] { DATAMEMBER = ...; } does not copy the member by value as a developer might expect; instead, it copies the pointer S* const this by value, causing two distinct hazards:
      1. Unintended Mutation of the Original Object: By the unified principle above, applying Top-Level const to S* const __this; leaves it S* const, so this->DATAMEMBER mutates the original object rather than a copy even without mutable.
      2. Dangling Pointer When Outliving the Object: If the lambda outlives the S object, such as when returned from the member function or registered as an asynchronous callback, the original object is destroyed first and dereferencing __this causes a Dangling Pointer (UB).
    • To prevent this confusion, C++20 deprecated implicit capture of this via [=]. Always state your intent explicitly:
SyntaxMember Generated in Closure ClassMutation & Lifetime Behavior
[this] (or [=, this])S* const __this; (pointer copy)Directly modifies original this->DATAMEMBER even without mutable, Dangling Pointer risk if object dies
[*this] (C++17)S __this; (full object copy)Creates an independent copy of S, copy cannot be modified without mutable
[DATAMEMBER = DATAMEMBER] (C++14 init-capture)TYPE DATAMEMBER; (copy of single member)Safely copies only that single member into the closure
struct S {
    int i = 0;

    void run() {
        // auto bad = [i] { return i; };      // ❌ Compile error: cannot capture class member directly
        auto ptr_cap = [this] { i = 1728; };  // ✅ Valid: captures S* const -> modifies original this->i even without mutable
        auto obj_cap = [*this] { return i; }; // ✅ Valid: copies entire S object by value -> independent of original
        auto mem_cap = [i = i] { return i; }; // ✅ Valid: C++14 init-capture copies only member i by value
        ptr_cap();
    }
};

6. Capture List Summary and Syntax Rules#

Capture SyntaxMeaning
[]Capture no external variables
[VAR1, &VAR2]Explicitly capture VAR1 by value and VAR2 by reference
[=]Implicitly capture by value all external variables referenced in the lambda body
[&]Implicitly capture by reference all external variables referenced in the lambda body
[=, &VAR]Implicitly capture all variables by value by default, except VAR explicitly by reference
[&, VAR]Implicitly capture all variables by reference by default, except VAR explicitly by value
  • Ordering Rule (Capture Default Must Come First):
    • Explicit variable captures can appear in any order relative to each other ([VAR1, &VAR2] and [&VAR2, VAR1] are both valid).
    • However, when mixing a capture-default (= or &) with explicit captures, the default must be the very first item in []. [=, &VAR] is valid, whereas [&VAR, =] is a compile error.
  • No Redundant Modes: Explicit captures following a default must use the opposite capture mode: &VAR after =, or by-value VAR after &, with the C++20 exception that both [=, this] and [=, *this] are allowed.