Boost logo

Boost Users :

From: TomJordan (tomjordan766_at_[hidden])
Date: 2019-08-12 15:54:45


Hi,
I'm just starting to use ASIO. I have been reading the C++11 HTTP Server example at https://www.boost.org/doc/libs/1_70_0/doc/html/boost_asio/example/cpp11/http/server/ and want to make sure I understand use of shared_ptr in this example, because I didn't notice any explanation in the documentation.

The connection class inherits from std::enable_shared_from_this<connection>, and is then passed in a shared_ptr (the captured 'self') to the handler function registered with the async_read_some in connection::do_read(). Is this approach, and the related design decsision that the server creates a shared_ptr to a new connection in its server::do_accept() function, taken simply in order to ensure that the connection object is kept alive for as long as any asynchronous read/write operation requires it?

So is it implying that if the connection was NOT kept alive by a shared_ptr (i.e., was instead created by the server and stored by value in a std container) something bad could and likely would happen at some point, most likely due to the handler being called on an object that no longer exists? This might be when a boost::asio::error::operation_aborted is reported by the handler, when a current async operation is cancelled during the server/connection_manager shutdown process as a result of closing the socket, after the connection object value has been removed from the container, for example?

Is this shared_ptr approach the idiomatic or even the only way to manage lifetimes in ASIO async calls? It just looks a bit ugly to me, bloats the code a bit and I was wondering if there is any other way to do it without the intrusion of shared_ptrs into the mix?

Tom


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net