dshepherd
dshepherd

Reputation: 5417

Why capture this as well as shared-pointer-to-this in lambdas?

In the Boost.asio C++11 examples there are snippets like the following:

void do_read()
{
  auto self(shared_from_this());
  socket_.async_read_some(boost::asio::buffer(data_, max_length),
      [this, self](boost::system::error_code ec, std::size_t length)
      {
        if (!ec)
        {
          do_write(length);
        }
      });
}

I understand why the self pointer is needed to keep the class alive (see this question), but I don't understand why the this pointer is also captured. Is it just so that the author can write do_write(length) instead of self->do_write(length) or is there another reason?

Upvotes: 16

Views: 2901

Answers (2)

The Quantum Physicist
The Quantum Physicist

Reputation: 26356

The answer given up there is ABSOLUTELY wrong! You should not pass both! Here's how you should do it, based on your code, without passing this:

void do_read()
{
  auto self(shared_from_this());
  socket_.async_read_some(boost::asio::buffer(data_, max_length),
      [self](boost::system::error_code ec, std::size_t length)
      {
        if (!ec)
        {
          self->do_write(length);
        }
      });
}

Upvotes: 3

Violet Giraffe
Violet Giraffe

Reputation: 33627

Without this captured, you cannot call methods of the class from inside the lambda (e. g. do_write). Or access member variables. Granted, you could instead write self->do_write(), but it's both less elegant and potentially slower (because of the shared_ptr involved).

Upvotes: 6

Related Questions