Cheat Sheet
- Linux: /linux/
- CLI: /linux/cli/
- locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/
- make: /linux/cli/make/
- awk: /linux/cli/awk/
- find: /linux/cli/find/
- grep: /linux/cli/grep/
- pgrep: /linux/cli/pgrep/
- ps: /linux/cli/ps/
- pstree: /linux/cli/pstree/
- trap: /linux/cli/trap/
- xargs: /linux/cli/xargs/
- Shell: /linux/shell/
- BASH_SOURCE: /linux/shell/bash-source/
- Redirection: /linux/shell/redirection/
- Special Variables: /linux/shell/special-variables/
- Scripting Tips: /linux/shell/script-tips/
- set -o vi: /linux/shell/bash-vi-mode/
- Shell Processing Order: /linux/shell/process-order/
- What are Interactive and Login Shells?: /linux/shell/interactive-login/
- Double Quote Expansion: /linux/shell/shell-expansion/
- System Programming: /linux/system-programming/
- File I/O: /linux/system-programming/file-io/
- Process: /linux/system-programming/process/
- Shared Libraries: /linux/system-programming/shared-libraries/
- Kernel: /linux/kernel/
- Go: /programming/go/
- Concurrency: /programming/go/concurrency/
- CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/
- Channel: /programming/go/concurrency/channel/
- Select: /programming/go/concurrency/select/
- sync: /programming/go/concurrency/sync/
- Concurrency Patterns: /programming/go/concurrency/patterns/
- Goroutines and the Go Runtime: /programming/go/concurrency/runtime/
- Standard Library: /programming/go/std/
- os: /programming/go/std/os/
- context: /programming/go/std/context/
- io: /programming/go/std/io/
- json: /programming/go/std/json/
- net/http: /programming/go/std/net-http/
- slog: /programming/go/std/slog/
- testing: /programming/go/std/testing/
- time: /programming/go/std/time/
- Ellipsis (...): /programming/go/ellipsis/
- error: /programming/go/error/
- Function: /programming/go/function/
- Go Tool: /programming/go/tool/
- Interface: /programming/go/interface/
- Map: /programming/go/map/
- Package and Module: /programming/go/package-module/
- Pointer: /programming/go/pointer/
- Slice: /programming/go/slice/
- String: /programming/go/string/
- Switch: /programming/go/switch/
- Comparison: /programming/go/comparison/
- defaultdict: /programming/python/collections/defaultdict/
- heapq: /programming/python/collections/heapq/
- @cache: /programming/python/cache/
- abc: /programming/python/abc/
- bisect: /programming/python/bisect/
- Type Hints: /programming/python/type-hints/
- Passing Mechanism: /programming/python/passing-mechanism/
- uv: /programming/python/uv/
- *args and **kwargs: /programming/python/args-kwargs/
- re: /programming/python/re/
- C: /programming/c/
- Pointers and Arrays: /programming/c/pointer/
- Syntax Basics: /programming/c/syntax-basics/
- static: /programming/c/static/
- Bit Manipulation: /programming/c/bit-manipulation/
- C vs C++: /programming/c/c-vs-cpp/
- stdatomic: /programming/c/stdatomic/
- C++: /programming/cpp/
- RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/
- Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/
- Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/
- C++ Keywords Reference: /programming/cpp/keywords/
- C++ Primer: /programming/cpp/primer/
- Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/
- Expressions: /programming/cpp/primer/expressions/
- Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/
- Statements: /programming/cpp/primer/statements/
- Functions: /programming/cpp/primer/functions/
- Classes: /programming/cpp/primer/classes/
- The IO Library: /programming/cpp/primer/io-library/
- STL: /programming/cpp/primer/stl/
- Lambda Expressions: /programming/cpp/primer/lambda/
- Smart Pointers: /programming/cpp/primer/smart-pointers/
- Copy Control: /programming/cpp/primer/copy-control/
- Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/
- Object-Oriented Programming (OOP): /programming/cpp/primer/oop/
- Templates and Generic Programming: /programming/cpp/primer/templates/
- Namespaces: /programming/cpp/primer/namespaces/
- Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/
- Advanced: /programming/cpp/advanced/
- Error Handling: /programming/cpp/advanced/error-handling/
- Concurrency & Threading: /programming/cpp/advanced/concurrency/
- Unit Testing: /programming/cpp/advanced/unit-testing/
- Comparison: /programming/comparison/
- Kubernetes: /cloud-devops/kubernetes/
- Fleet: /cloud-devops/kubernetes/gke/fleet/
- Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/
- API Extension: /cloud-devops/kubernetes/api-extension/
- Concept: /cloud-devops/kubernetes/kueue/concept/
- DRA: /cloud-devops/kubernetes/dra/
- Secret Manager: /cloud-devops/terraform/google-secret-manager/
- Knowledge: /network/knowledge/
- PDU: /network/knowledge/osi-model/
- curl: /network/cli/curl/
- Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/
- Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/
- Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/
- Regular Expression: /cs/regular-expression/
- Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/
- Driver and Runtime: /ai-ml/gpu/driver-and-runtime/
- Serving: /ai-ml/serving/
- Dotfiles: /dotfiles/
- Git: /dotfiles/git/
- Cheat Sheet: /dotfiles/git/cheat-sheet/
- revisions: /dotfiles/git/revisions/
- Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/
- checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/
- rebase: /dotfiles/git/rebase/
- Branching and Merging: /dotfiles/git/branching-merging/
- Vim: /dotfiles/vim/
- Plugin: /dotfiles/vim/plugin/
- auto-pairs: /dotfiles/vim/plugin/auto-pairs/
- vim-commentary: /dotfiles/vim/plugin/vim-commentary/
- vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/
- vim-surround: /dotfiles/vim/plugin/vim-surround/
- Marks: /dotfiles/vim/tips/marks/
- vimrc: /dotfiles/vim/vimrc/
- lf: /dotfiles/lf/
# Lambda Expressions
Summary based on *C++ Primer, 5th ed.* Chapter 10.3 and Chapter 14.8.1.
## 1. Syntax and Under-the-Hood Mechanism
```cpp
[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**.
```cpp
// 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`]({{< relref "/programming/cpp/primer/variables-and-basic-types.md#top-level-vs-low-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 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 `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.
```cpp
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).
```cpp
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](#2-the-core-unified-principle-two-steps-govern-every-capture--const-case), 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:
| 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 |
```cpp
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.
- **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.