I'm 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
pervading this example. I couldn't see any direct explanation in the documentation.
I assume that the reason that connection inherits from std::enable_shared_from_this<connection>
, and is then passed in a shared_ptr
(the captured self
) to the handler registered with the the async_read_some
in connection::do_read()
, is to ensure that the connection
object is kept alive for as long as the asynchronous read operation requires it. The server
class creates a shared_ptr
to a new connection in its server::do_accept()
function accordingly.
I infer therefore that if the shared_ptr
based design was not used (i.e., connection
object just allocated on the stack in a std::set<connection>
connections_ held by connection_manager
instead of std::set<connection_ptr>
and only this
is captured by the handler passed to socket_.async_read_some
), something unpleasant could happen due to an outstanding async_read_some
handler's call occurring after the connection
object no longer existed.
My question (assuming my previous understanding is correct) is, how necessary is all this use of shared_ptr
/shared_from_this()
and what circumstance(s) would lead to such an occurrence if no shared_ptr
s were used, since a stack allocated connection
would live for the duration of the connection_manager/server that owns it.