voidtest_init_capture(){ auto pw_outer = std::make_unique<Widget>("widget"); // test init capture. [pw = std::move(pw_outer)] { std::cout << *pw.get(); }(); [pw = std::make_unique<Widget>("widget2")] { std::cout << *pw.get(); }(); auto pw = std::make_unique<Widget>("test"); // test class member capture. pw->test_capture_member(); }
Captures apply only to non-static local variables (including parameters) visible in the scope where the lambda is created. So if you want to capture a class member, the original way is using a local variable. For example:
Since C++14, we can use init capture feature for this situation. It means we can define a new variable and initialize this local variable using class member during lambda capture. For example: