C++
Capture modes
Learn capture modes with [=], [&] and [this].
Capture modes
The capture clause sets how a lambda captures variables from its surroundings. There are three main modes: [=] captures all variables by value (copy), [&] captures all variables by reference, [this] captures the class this pointer.
With by-value capture the lambda takes a copy; it does not modify the outer variable. With by-reference capture the lambda accesses the outer variable directly; changes propagate outside. You can capture a single variable too: [&count] captures only count by reference. Mixed modes are possible: [=, &count] captures all by value and count by reference.
Value vs reference
By-value capture [=] creates a copy. Even if you modify the variable inside the lambda, the outer variable does not change. By-reference capture [&] gives direct access; changes inside the lambda affect the outer variable.
Example: int n = 0; auto f = [&n]() { n++; }; f(); f(); leaves n at 2. Because the lambda captured n by reference and incremented it each call. If we had used [=], n would not change; the copy inside the lambda would increment but not propagate. Be careful with by-reference capture: the lambda must be used while the reference is still valid.
Exercise Increment a counter by reference
Define int count = 0;. Assign the lambda [&count]() { count++; } to the variable increment. Call the lambda twice and print count with std::cout.
Show example solution
#include <iostream>
int main() {
int count = 0;
auto increment = [&count]() { count++; };
increment();
increment();
std::cout << count;
return 0;
}
Test yourself
-
Match each capture mode to its meaning
- [=]
- Capture by value
- [&]
- Capture by reference
- [this]
- Class pointer
- [&count]
- Single variable reference
-
Complete the reference capture
int count = 0;
auto f = [____]() { count++; };
Show answer
int count = 0;
auto f = [&count]() { count++; };
-
Which capture mode can modify an outer variable?
int n = 0;
auto f = ???() { n++; };
- [=] (by value)
- [] (no capture)
- [this]
- [&] (by reference)
Show answer
[&] (by reference) — [&] captures by reference and can modify the outer variable.
Next lesson: Lambdas with STL