Capturing *this in C++11, 14 and 17

A common need in asynchronous programming is the ability to use *this inside a callback.

In C++11 if you want to create a copy of *this you’d introduce a new lvalue:

auto self = *this;
client->request([self]() {
    self.logger->log("Completed request!");
});

C++14 allows initialization expressions inside the lambda capture. Doing so is helpful for working with move semantics but also allows us to get rid of a line from the C++11 example above.

client->request([self = *this]() {
    self.logger->log("Completed request!");
}); 

With C++17 you can create a copy of *this by doing the following. Note that doing so no longer allows you to use the original pointer this inside the lambda body (unless you created a separate lvalue for it).

client->request([=, *this]() {
    logger->log("Completed request!");
    // "this" is no longer from the outside scope
});

For more info on C++17 lambda capture off *this, visit: P0018R3 Lambda Capture of *this by Value as [=,*this]

Leave a Reply

Your email address will not be published. Required fields are marked *