C++ › Lambda Expressions

What is the capture list in a lambda?

Beginner

Answer

The capture list [...] specifies which surrounding variables the lambda can use and how. [x] captures x by value (a copy), [&x] by reference, [=] captures all used variables by value, [&] all by reference, and [this] captures the enclosing object. Captures let the lambda access local state.
int n = 10;
auto byVal = [n]()  { return n; };   // copy
auto byRef = [&n]() { n++; };        // reference
Real-world example A lambda captures a threshold value by value so it can filter a collection with std::count_if.

Common follow-ups: By value vs by reference capture? | What does [=] capture?