Developer Blog‎ > ‎

Using the lambda capture list explicitly

posted Jun 24, 2013, 8:53 AM by Derick Janssen   [ updated Aug 1, 2013, 1:07 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
Comments