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

左心房为你撑大大i 提交于 2019-12-22 07:01:28

问题


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());
```

回答1:


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.



来源:https://stackoverflow.com/questions/29613178/why-the-boost-example-calls-shared-from-this-again-instead-of-using-the-clos

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!