This is called lambda capture and it's what the leading square brackets in a lambda expression are about. You basically have two options:
- By-value capture:
auto f = [x](){ std::cout << x; };
Lambda object receives its own private copy of the object so any subsequent changes to the outer x
have no effect on the lambda. A special capture =
captures by-value every free variable in the lambda's code not captured before it:
double x = 40, y = 2;
auto f = [=]{ return x + y; };
- By-reference capture:
auto f = [&x](){ std::cout << x; };
Lambda object accesses an outer scope object by reference, so the subsequent changes to the outer x
become known to the lambda. A special capture &
captures by-reference every free variable in the lambda's code not captured before it:
double x = 40, y = 0;
auto f = [&]{ return x + y; };
y = 2;