Advertisement
Beginner C++, Lambda Expressions

What is the capture list in a lambda?

Short 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.

Save C++ mock interview
Advertisement
AModel 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.
Likely follow-ups
  • By value vs by reference capture? | What does [=] capture?
Related topics