Functions
F.54
When writing a lambda that captures `this` or any class data member, don't use `[=]` default capture
Reason
It's confusing. Writing [=] in a member function appears to capture by value, but actually captures data members by reference because it actually captures the invisible this pointer by value. If you meant to do that, write this explicitly.
Example
class My_class {
int x = 0;
// ...
void f()
{
int i = 0;
// ...
auto lambda = [=] { use(i, x); }; // BAD: "looks like" copy/value capture
x = 42;
lambda(); // calls use(0, 42);
x = 43;
lambda(); // calls use(0, 43);
// ...
auto lambda2 = [i, this] { use(i, x); }; // ok, most explicit and least confusing
// ...
}
};
Note
If you intend to capture a copy of all class data members, consider C++17 [*this].
Enforcement
- Flag any lambda capture-list that specifies a capture-default of
[=]and also capturesthis(whether explicitly or via the default capture and a use ofthisin the body)