Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the boost example calls `shared_from_this()` again instead of using the closure variable

In the connection object at the boost asio HTTP server example in methods do_read and do_write the shared_from_this() is captured to address the connection object lifespan issue, as been answered previously. It is still not clear why on lines 67 and 88 the code calls shared_from_this() again, instead of using self:

40  auto self(shared_from_this());
41  socket_.async_read_some(boost::asio::buffer(buffer_),
42      [this, self](boost::system::error_code ec, std::size_t bytes_transferred)
43      {
....
67          connection_manager_.stop(shared_from_this());
```
like image 372
Vlad Didenko Avatar asked Apr 13 '15 19:04

Vlad Didenko


1 Answers

There is no practical reason for that (I guess it's just a leftover from older C++03 example that was refactored to C++11 style). Using self would be preferable, as it's already captured anyway.

The only "educational" reason I can think of could be to demonstrate that the explicitly captured self is stored within the lambda, even if it's unused.

like image 146
Igor R. Avatar answered Oct 23 '22 10:10

Igor R.