Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.asio and asynchronous chain, unique_ptr?

Tags:

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

like image 515
Germán Diago Avatar asked May 09 '16 06:05

Germán Diago


2 Answers

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.

like image 185
Richard Hodges Avatar answered Sep 28 '22 03:09

Richard Hodges


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

like image 38
sehe Avatar answered Sep 28 '22 04:09

sehe