Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 399
dshepherd Avatar asked Jan 11 '16 10:01

dshepherd


2 Answers

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

like image 170
Violet Giraffe Avatar answered Nov 20 '22 07:11

Violet Giraffe


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);
        }
      });
}
like image 24
The Quantum Physicist Avatar answered Nov 20 '22 07:11

The Quantum Physicist