Capture by reference lets a lambda update a variable outside the lambda body.

reference capture When a lambda captures by reference, it works with the original variable.

Capture By Reference

increment
capture_by_reference.cpp
Replay: real traced execution (multi-file project)
#include <iostream>

int main() {
    int increment = 3;
    int total = 0;

    auto addToTotal = [&total](int value) {
        total += value;
    };

    addToTotal(increment);
    addToTotal(2);

    std::cout << "increment=" << increment << std::endl;
    std::cout << "total=" << total << std::endl;
    return 0;
}
#include <iostream>

int main() {
    int increment = 1;
    int total = 0;

    auto addToTotal = [&total](int value) {
        total += value;
    };

    addToTotal(increment);
    addToTotal(2);

    std::cout << "increment=" << increment << std::endl;
    std::cout << "total=" << total << std::endl;
    return 0;
}
#include <iostream>

int main() {
    int increment = 5;
    int total = 0;

    auto addToTotal = [&total](int value) {
        total += value;
    };

    addToTotal(increment);
    addToTotal(2);

    std::cout << "increment=" << increment << std::endl;
    std::cout << "total=" << total << std::endl;
    return 0;
}
  1. increment ← 3, total ← 0, addToTotal ← (empty)

    3int main() {4    int increment→ 3 = 3; //@increment=1, 55    int total→ 0 = 0;67    auto addToTotal→ (empty) = [&total](int value) {8        total += value;9    };1011    addToTotal(empty)(increment3);12    addToTotal(empty)(2);1314    std::cout << "increment=" << increment3 << std::endl;15    std::cout << "total=" << total5 << std::endl;16    return 0;17}
    outputincrement=3
    total=5
  1. increment ← 1, total ← 0, addToTotal ← (empty)

    3int main() {4    int increment→ 1 = 1;5    int total→ 0 = 0;67    auto addToTotal→ (empty) = [&total](int value) {8        total += value;9    };1011    addToTotal(empty)(increment1);12    addToTotal(empty)(2);1314    std::cout << "increment=" << increment1 << std::endl;15    std::cout << "total=" << total3 << std::endl;16    return 0;17}
    outputincrement=1
    total=3
  1. increment ← 5, total ← 0, addToTotal ← (empty)

    3int main() {4    int increment→ 5 = 5;5    int total→ 0 = 0;67    auto addToTotal→ (empty) = [&total](int value) {8        total += value;9    };1011    addToTotal(empty)(increment5);12    addToTotal(empty)(2);1314    std::cout << "increment=" << increment5 << std::endl;15    std::cout << "total=" << total7 << std::endl;16    return 0;17}
    outputincrement=5
    total=7