Search code examples
c++c++11boostlambdaboost-asio

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?


Solution

  • 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).