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:
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 ...