Lambda captures in C++
The capture list decides what a lambda can see: a private copy with [base], live access with [&total].
#include <vector>
int capture_demo() {
int base = 10;
int total = 0;
auto add_base = [base](int x) { return x + base; }; // copy of base
auto tally = [&total](int x) { total += x; }; // writes through
for (int n : std::vector<int>{1, 2, 3}) {
tally(add_base(n));
}
return total;
}
How it works
add_basecapturesbaseby value, so it carries its own copy of10wherever it goes.tallycapturestotalby reference and writes straight through to the local variable.- The range-for feeds each element through both lambdas, leaving the sum in
total.
Keywords and builtins used here
autocapture_demoforintreturn
The run, in numbers
- Lines
- 12
- Characters to type
- 289
- Tokens
- 91
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 78 seconds.
Step 2 of 3 in Functions & lambdas, step 11 of 27 in Language basics.