Search⌘ K
AI Features

Capturing [*this] in Lambda Expressions

Explore how to capture the this pointer in lambda expressions within class methods in C++17. Understand the difference between capturing this by pointer and capturing the whole object by value using [*this]. Learn why capturing this can lead to dangling pointers and how C++17 enhances safety and clarity in lambda captures, especially in asynchronous or multithreaded contexts.

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:

C++ 17
#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 ...