Post date: Jun 24, 2013 3:53:44 PM
This serves mostly as an easy to find reference for C++ 11 lambda capture lists with an example. Since at the time this is not easily found with a good example.
Most examples I've found use [] (none) or [&] (all) but not anything more explicit than that.
Documentation from: https://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B
[] //no variables defined. Attempting to use any external variables in the lambda is an error.[x, &y] //x is captured by value, y is captured by reference[&] //any external variable is implicitly captured by reference if used[=] //any external variable is implicitly captured by value if used[&, x] //x is explicitly captured by value. Other variables will be captured by reference[=, &z] //z is explicitly captured by reference. Other variables will be captured by value
Example Code:
unsigned int uiNegative(0); auto AddIfNegative([&uiNegative](int iValue) { if (iValue < 0) uiNegative += iValue * -1; });
AddIfNegative(4); AddIfNegative(-5); AddIfNegative(6); AddIfNegative(-7); AddIfNegative(8);
std::cout << uiNegative << std::endl;
Results:
prints: 12