typestar

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

  1. add_base captures base by value, so it carries its own copy of 10 wherever it goes.
  2. tally captures total by reference and writes straight through to the local variable.
  3. The range-for feeds each element through both lambdas, leaving the sum in total.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Functions & lambdas, step 11 of 27 in Language basics.

← Previous Next →