bad_weak_ptr在使用继承自boost :: asio :: io_context :: service的类时

时间:2018-06-10 15:43:14

标签: c++ websocket connection boost-asio boost-beast

我开始练习使用boost asio&提升野兽来开发自己的基本服务器和连接类。最近我遇到了bad_weak_ptr异常,我无法弄清楚如何管理问题。这是代码:

class server : public boost::asio::io_context::service
    {
        tcp::endpoint endpoint{ boost::asio::ip::address_v6::any(), 7654 };
        tcp::acceptor acceptor;
        boost::asio::strand<boost::asio::io_context::executor_type> strand;
        std::vector<std::weak_ptr<tcp_connection_ui>> connections;
    public:
        static const boost::asio::execution_context::id id;

        explicit tcp_server_ui(boost::asio::io_context& ioc)
            : boost::asio::io_context::service{ ioc }
            , acceptor{ ioc, endpoint }
            , strand{ ioc.get_executor() }
        {
        }

        void run()
        {
            boost::asio::post(strand, [this] {start_accept(); });
        }

        void start_accept()
        {
            tcp::socket socket{ acceptor.get_io_context() };
            tcp_connection_ui::pointer new_connection =
                tcp_connection_ui::create(std::move(socket));

            connections.push_back(new_connection);

            acceptor.async_accept(new_connection->web_socket().next_layer(),
                boost::asio::bind_executor(strand, std::bind(
                    &tcp_server_ui::handle_accept,
                    this, new_connection, std::placeholders::_1)));
        }

        void handle_accept(tcp_connection_ui::pointer new_connection,
            boost::system::error_code ec)
        {
            if (!ec) {
                new_connection->run();
            }

            start_accept();
        }

        void broadcast(std::string&& msg)
        {
            std::cout << '+' << std::endl;
            if (connections.empty())
                return;

            for (auto const & x : connections)
                x.lock()->enqueue_message(std::move(msg));
        }
    };

还有代码停止运行的地方:

class tcp_connection_ui : std::enable_shared_from_this<tcp_connection_ui>
    {
    public:
        using pointer = std::shared_ptr<tcp_connection_ui>;

        static pointer create(tcp::socket socket)
        {
            return std::make_shared<tcp_connection_ui>(tcp_connection_ui{ std::move(socket) });
        }

        void run()
        {
            ws.async_accept(boost::asio::bind_executor(strand, std::bind(
                &tcp_connection_ui::on_accept, shared_from_this(),
                std::placeholders::_1)));
        } .../};

如果客户端尝试在server :: handle_accept中连接值shared_from_this等于_Wptr = empty。我认为我在理解io_context :: service和/或shared_from_this功能方面遇到了一些麻烦。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

必须公开继承基类:

class tcp_connection_ui : public std::enable_shared_from_this<tcp_connection_ui>

否则,make_sharedshared_ptr将不会注意到它,并且随后无法初始化&#34;隐藏&#34;的weak_ptr