Capture List and Classes ⇝
• [this] captures the current object (*this) by-reference (implicit in C++17)
• [x = x] captures the current object member x by-value C++14
• [&x = x] captures the current object member x by-reference C++14
• [=] default capture of this pointer by value has been deprecated C++20
class A {
int data = 1;
void f() {
int var = 2; // <-- local variable
auto lambda1 = [=]() { return var; }; // copy by-value, return 2
auto lambda2 = [=]() { int var = 3; return var; }; // return 3 (nearest scope)
auto lambda3 = [this]() { return data; }; // copy by-reference, return 1
auto lambda4 = [*this]() { return data; }; // copy by-value (C++17), return 1
// auto lambda5 = [data]() { return data; }; // compile error 'data' is not visible
auto lambda6 = [data = data]() { return data; }; // return 1
}
};
34/62