问题
I'm checking this SSL server example and wondering why using shared_ptr
. It start with the following method (do_accept()
) and continuously using auto self(shared_from_this())
in the session
class to extend its lifespan between handlers.
Q: Is it possible to use a tcp::socket
member inside session
class and avoid shared_ptr
? What modification must be applied?
void do_accept()
{
acceptor_.async_accept(
[this](const boost::system::error_code& error, tcp::socket socket)
{
if (!error)
{
std::make_shared<session>(std::move(socket), context_)->start();
}
do_accept();
}
);
}
Inside session
class:
void do_handshake()
{
auto self(shared_from_this());
socket_.async_handshake(boost::asio::ssl::stream_base::server,
[this, self](const boost::system::error_code& error)
{
if (!error)
{
do_read();
}
}
);
}
来源:https://stackoverflow.com/questions/61055104/why-using-shared-ptr-in-this-boost-ssl-server-example