Why using shared_ptr in this boost SSL server example

纵然是瞬间 提交于 2020-04-16 05:48:39

问题


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

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