1

I develop a desktop chat with boost asio and beast (for browser support).

I use this architecture : enter image description here

But, when building, I have an issue : bad_weak_ptr, I don't know what is wrong :s Here a link to the source https://onlinegdb.com/BkFhDGHe4

Update1 : I remove run() function into constructor and move it into handle_accept function, tcp_server class. like this:

void tcp_server::handle_accept(const boost::system::error_code ec, websocket_session_ptr new_websocket) { if (!ec) { // Happens when the timer closes the socket if(ec == boost::asio::error::operation_aborted) return; new_websocket->run(); //Here chatwebsocketsessionpointer session = chat_websocket_session::create(room, new_websocket); room->join(session); wait_for_connection(); } } I can see the chat_webocket_session is deleted, but still have issue with bad_weak_ptr

Update 2 : I found where is the issue. If I never call do_read() function, there is no error, and I can connect to server with ws If I call it into wait_for_data from chat_websoket_session class, I have issue. So I must found how call do_read()

Update 3 : If I do websocket_session_ptr new_websocket(new websocket_session(std::move(socket))); acceptor.async_accept( socket, boost::bind( &tcp_server::websocket_accept, this, boost::asio::placeholders::error, new_websocket ));

making ref to : boost beast websocket example, I accept first the socket, and after I accept the websocket with m_ws.async_accept() but I have now Bad file descriptor which means the socket is not open.

P.S: I update the ide URL (GDB online debugger)

4

1 回答 1

3

您正在从构造函数内部使用指向 this 的共享指针:

websocket_session::websocket_session(tcp::socket socket)
        : m_ws(std::move(socket))
        , strand(socket.get_executor())
{
    run();
}

run()你里面做

void websocket_session::run() {
    // Accept the websocket handshake
    std::cout << "Accepted connection" << std::endl;
    m_ws.async_accept(boost::asio::bind_executor(
        strand, std::bind(&websocket_session::on_accept, , std::placeholders::_1)));
}

使用shared_from_this()which 将尝试锁定未初始化weak_ptrenable_shared_from_this. 正如您在引发异常的文档std::bad_weak_ptr中看到的那样(广告 11)

shared_from_this明确警告这一点的文档:

只允许在先前共享的对象上调用 shared_from_this,即在由 std::shared_ptr 管理的对象上(特别是,shared_from_this 不能在构造函数中调用)。

于 2018-12-15T19:22:00.490 回答