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_TYPEare 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:
- 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. - The parameter list
(PARAMETER_LIST)and body{ /* FUNCTION_BODY */ }become the class’s overloaded function-call operatoroperator(). - Crucially,
operator()is generated as aconstmember functionoperator()(PARAMETER_LIST) constby default.
- Items in the capture list
- A lambda expression is syntactic sugar for an unnamed Closure class and a temporary Closure object generated automatically by the compiler:
// 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
- Step 1 — Capture
[]Declares Data Members: The capture list simply determines what member types are declared inside the compiler-generated Closure class.- Step 2 — Default
operator()() constApplies Only Top-Levelconst: Withoutmutable, every data member receives Top-Levelconstonly. Addingmutableremoves only that Top-Levelconst, and can never strip away a member’s existing Low-Levelconst.
Whether capturing by value, by reference, or via this, there are zero exceptions:
| Capture Item | Step 1: Member Generated in Closure Class | Step 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
constandmutable:- Applying top-level
consttosize_t v1;producesconst size_t, disallowing mutation insideoperator()() const. - Adding
mutableomitsconstfromoperator()(), allowing modification of the internal copied member without affecting the outer variable.
- Applying top-level
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 memberint& x;. Because a reference is inherently Top-Levelconst, applying Top-Levelconstleaves the referencedintnon-const, so outerxcan be mutated even when the lambda itself is declaredconst auto lam = ...;below. - Conversely, for
const int cx,[&cx]declaresconst int& cx;with Low-Levelconstfrom the start, so evenmutablecannot make it modifiable.
- For
- 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 pointerS* const thisby value, causing two distinct hazards:- Unintended Mutation of the Original Object: By the unified principle above, applying Top-Level
consttoS* const __this;leaves itS* const, sothis->DATAMEMBERmutates the original object rather than a copy even withoutmutable. - Dangling Pointer When Outliving the Object: If the lambda outlives the
Sobject, such as when returned from the member function or registered as an asynchronous callback, the original object is destroyed first and dereferencing__thiscauses a Dangling Pointer (UB).
- Unintended Mutation of the Original Object: By the unified principle above, applying Top-Level
- To prevent this confusion, C++20 deprecated implicit capture of
thisvia[=]. Always state your intent explicitly:
- Writing
| Syntax | Member Generated in Closure Class | Mutation & 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 Syntax | Meaning |
|---|---|
[] | 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.
- Explicit variable captures can appear in any order relative to each other (
- No Redundant Modes: Explicit captures following a default must use the opposite capture mode:
&VARafter=, or by-valueVARafter&, with the C++20 exception that both[=, this]and[=, *this]are allowed.