Codiqo

Learn C++ · lesson 55 of 61 · about 9 minutes

Captures

Let a lambda use variables from around it, by copy or by reference.

What you'll learn

  • Capture a variable by value with [x] or [=]
  • Capture by reference with [&x] or [&]
  • Choose the right capture

The toll bridge

Past the tower, a troll guards the bridge over the moat and asks a toll, which the player types. The adventure counts the chests from the treasure room that would cover the toll on their own, then the hero pays it from the gold carried, if there's enough: You pay 10 gold. Gold: 70. A toll of 0 or less and the troll just waves the hero across. Both jobs are lambdas, and both need something from outside them: the toll, and the hero's gold.

Reaching outside the lambda

A lambda can't see the local variables around it unless you list them in the square brackets. That's called capturing.

  • [limit] copies limit into the lambda
  • [&total] uses total itself, by reference, so the lambda can change it
  • [=] copies everything it uses; [&] references everything it uses

Capturing a limit

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> scores = {45, 72, 90, 38, 66};
    int pass = 60;
    auto passed = std::count_if(scores.begin(), scores.end(), [pass](int s) { return s >= pass; });
    std::cout << passed << " passed\n";
}

Output

3 passed

Copy or reference?

A copy is taken when the lambda is made, so later changes to the original don't affect it. A reference always sees the current value and lets the lambda change it. Use a reference when the lambda should update something, like a running total.

The difference

#include <iostream>

int main() {
    int n = 1;
    auto by_copy = [n]() { return n; };
    auto by_ref = [&n]() { return n; };
    n = 50;
    std::cout << by_copy() << " " << by_ref() << "\n";

    int total = 0;
    auto add = [&total](int x) { total += x; };
    add(5);
    add(7);
    std::cout << total << "\n";
}

Output

1 50
12

A copy of the toll, the real gold

covers only reads the toll, so [toll] copies it in, and count_if calls it once for every chest. pay has to take money away, and the hero's gold has to stay spent afterwards, so it captures [&gold] and changes the real variable. pay also gives back true or false, so the adventure knows whether the hero paid.

Tip

Listing captures by name, like [pass] or [&total], makes it clear what the lambda depends on. [=] and [&] are handy, but hide that.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.