C++11 lambda capture `this` and capture local variables by value
As cppreference says:
[=] captures all automatic variables used in the body of the lambda by copy and current object by reference if exists
[=]
does what you want -- it captures anything not a member variable by value, and *this
by reference (or this
by value).
[*this,=]
captures both local variables and the object by value in c++17.
[&]
captures local variables by reference and *this
by reference or this
(the pointer) by value.
Both default capture modes capture this
the same way. Only in c++17 can you change that.
[=]
already captures this
by value. Take a look at the following code live here: http://cpp.sh/87iw6
#include <iostream>
#include <string>
struct A {
std::string text;
auto printer() {
return [=]() {
std::cout << this->text << "\n";
};
}
};
int main() {
A a;
auto printer = a.printer();
a.text = "Hello, world!";
printer();
}