...

/

Capturing [*this] in Lambda Expressions

Capturing [*this] in Lambda Expressions

Let's look at how to capture [*this] in Lambda Expressions.

We'll cover the following...

When you write a lambda inside a class method, you can reference a member variable by capturing this. For example:

Press + to interact
#include <iostream>
#include <string>
struct Test {
void foo() {
std::cout << m_str << '\n';
auto addWordLambda = [this]() { m_str += "World"; };
addWordLambda ();
std::cout << m_str << '\n';
}
std::string m_str {"Hello "};
};
int main() {
Test test;
test.foo();
return 0;
}

In the line with auto addWordLambda = [this]() {... } we capture this pointer and later we can access m_str.

Please notice that we captured this by value… to a pointer. You have access to the member variable, not its copy. The same effect happens when you capture by [=] or [&]. That’s why when ...