[英]shared_from_this throws bad_weak_ptr with boost::asio
[英]bad_weak_ptr with boost smart pointer
我使用boost asio和beast开发桌面聊天(用于浏览器支持)。
但是,在构建时,我有一个问题: bad_weak_ptr
,我不知bad_weak_ptr
什么问题:s这里是源代码的链接https://onlinegdb.com/BkFhDGHe4
Update1 :我将run()函数删除到构造函数中并将其移动到handle_accept函数tcp_server类中。 像这样:
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(); } }
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(); } }
我可以看到chat_webocket_session被删除,但仍然有问题与bad_weak_ptr
更新2:我发现了问题所在。 如果我从不调用do_read()函数,则没有错误,我可以用ws连接到服务器如果我从chat_websoket_session类调用wait_for_data,我就有问题了。 所以我必须找到如何调用do_read()
更新3:如果我做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 ));
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 ));
使ref成为: boost beast websocket示例 ,我首先接受套接字,然后我接受带有m_ws.async_accept()
的websocket但我现在有了Bad file descriptor
,这意味着套接字没有打开。
PS:我更新了ide URL(GDB在线调试器)
您正在构造函数中使用指向此的共享指针:
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()
,它将尝试从enable_shared_from_this
锁定unitialized weak_ptr
。 正如您在文档中看到的那样抛出std::bad_weak_ptr
异常( std::bad_weak_ptr
)
shared_from_this
的文档明确警告:
允许仅在先前共享的对象上调用shared_from_this,即在由std :: shared_ptr管理的对象上( 特别是,在构造函数中不能调用shared_from_this )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.