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?
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).
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);
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With