Class lambdas and capture of this
suggest changeA lambda expression evaluated in a class’ member function is implicitly a friend of that class:
class Foo
{
private:
int i;
public:
Foo(int val) : i(val) {}
// definition of a member function
void Test()
{
auto lamb = [](Foo &foo, int val)
{
// modification of a private member variable
foo.i = val;
};
// lamb is allowed to access a private member, because it is a friend of Foo
lamb(*this, 30);
}
};
Such a lambda is not only a friend of that class; it has the same access as the class in which it is declared.
Lambdas can capture the this pointer which represents the object instance the outer function was called on. This is done by adding this to the capture list:
class Foo
{
private:
int i;
public:
Foo(int val) : i(val) {}
void Test()
{
// capture the this pointer by value
auto lamb = [this](int val)
{
i = val;
};
lamb(30);
}
};
When this is captured, the lambda can use member names of its containing class as though it were in its containing class. So an implicit this-> is applied to such members.
Be aware that this is captured by value, but the value is the pointer, not a copy of the object. The lambda does not own that object. If the lambda outlives the object that created it, using the captured this is undefined.
This also means that the lambda can modify this without being declared mutable. It is the pointer which is const, not the object being pointed to. That is, unless the outer member function was itself a const function.
Also, be aware that the default capture clauses, both [=] and [&], also capture this implicitly, by the value of the pointer. Before C++17 it was an error to write this in the capture list when a default was given. Since C++17, [=, this] is allowed. Implicit capture of this by [=] is deprecated in C++20.
Since C++17, a lambda can capture a copy of the object *this, made when the lambda is created, by writing *this in the capture list:
class Foo
{
private:
int i;
public:
Foo(int val) : i(val) {}
void Test()
{
// capture a copy of the object given by the this pointer
auto lamb = [*this](int val) mutable
{
i = val;
};
lamb(30); // does not change this->i
}
};