Boost.asio and asynchronous chain, unique_ptr?

纵饮孤独 提交于 2020-07-06 12:24:28

问题


I am not deeply familiar with async programming and I have a question.

My question is the following. Given the echo_server example here for C++11 in boost.asio: http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/example/cpp11/spawn/echo_server.cpp

I would like to know if the std::make_shared<session> can be replaced in C++14 with a std::unique_ptr<session>in C++14, avoiding the overhead of reference count.

I am not sure since we have shared_from_this() but not something like unique_from_this(), so how can I access the unique_ptr<session> from inside this?.


回答1:


No, the use of shared_ptr in asio programming is idiomatic.

The idea is that the number of outstanding handlers is matched by the shared-count of the object initiating the async operations. This is achieved by binding a copy of the shared_ptr managing the object into the handler function objects.

The c++11/14 way would be to replace the boost::shared_ptr with std::shared_ptr (std::bind, lambdas, etc also work perfectly well with asio).

Update, now that I fully understand the question:

In the example you linked, I take it that you're referring to the shared_ptr called self which is created in the method go() ? You could write it without the shared_ptr if you wanted. You'd have to put a delete this as the last line of go(). You'd also have to remember to catch any exceptions to ensure this code path was taken. A unique_ptr could be set up to do this of course, but then you've got a lifetime management issue between the construction of the session and the successful creation of the adopting unique_ptr. shared_ptr eases the management burden for the cost of one atomic inc...

In which case the answer is strictly "yes", but imho I'll-advised as it's more brittle.




回答2:


As I understand it, your session object will go through a pipeline of handlers, one at a time. The state of your session is never shared. Why a unique_ptr would not make sense? The point is that when the latest handler is finished, the memory will be released. Does this hold true?

Yes, this is the trick. The library has been designed around copyable completion handlers.

If you worry about overhead, indeed avoid shared_ptr.

In that case, just carry a reference to some state with externally controlled lifetime. Just make sure it stays alive (just as you do with the io_service object itself).



来源:https://stackoverflow.com/questions/37109220/boost-asio-and-asynchronous-chain-unique-ptr

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