Capture all

In addition to capturing variables one by one, all variables in the scope can be captured by simply writing [=] or [&].

Using [=] means that every variable will be captured by value, whereas [&] captures all variables by reference.

If inside a class, it is also possible to capture the class member variables by reference using [this] and by copy by writing [*this]:

class Foo { 
public: 
 auto member_function() { 
   auto a = 0; 
   auto b = 1.0f;   // Capture all variables by copy 
   auto lambda_0 = [=]() { std::cout << a << b << m_; };    // Capture all variables by reference 
   auto lambda_1 = [&]() { std::cout << a << b << m_; };    // Capture member variables by reference 
   auto lambda_2 = [this]() { std::cout << m_; };    // Capture member variables ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.