Initializing variables in capture

As seen in the previous example, the capture scope initializes member variables in the corresponding class. This means that we can also initialize member variables inside a lambda, which are only visible from inside the lambda:

Lambda function...

...corresponding class:

auto func = [c=std::list<int>{4,2}](){  for(auto v : c)    std::cout << v;};func();// Output: 42 
class Func {public: Func() : c{4, 2} {} auto operator()()const->void{  for(auto v : c)    std::cout << v; }private: std::list<int> c;};auto func = Func{};func();// Output: 42

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.