gpt4 book ai didi

c++ - bad_weak_ptr with boost 智能指针

转载 作者:行者123 更新时间:2023-11-30 02:17:18 35 4
gpt4 key购买 nike

我使用 boost asio 和 beast(用于浏览器支持)开发桌面聊天。

我使用这个架构: enter image description here

但是,在构建时,我遇到了一个问题:bad_weak_ptr,我不知道哪里出了问题:s这是源代码的链接 https://onlinegdb.com/BkFhDGHe4

更新1:我将 run() 函数移除到构造函数中,并将它移到 handle_accept 函数中,tcp_server 类。像这样:


void tcp_server::handle_accept(const boost::system::error_code ec, websocket_session_ptr new_websocket)
{
如果 (!ec)
{
//当计时器关闭套接字时发生
如果(ec == boost::asio::error::operation_aborted)
返回;
new_websocket->run();//这里
chatwebsocketsessionpointer session = chat_websocket_session::create(room, new_websocket);
房间->加入( session );
等待连接();
}
}
我可以看到 chat_webocket_session 已删除,但 bad_weak_ptr

仍然存在问题

更新 2:我发现问题出在哪里。如果我从不调用 do_read() 函数,没有错误,我可以使用 ws 连接到服务器如果我从 chat_websoket_session 类将它调用到 wait_for_data 中,我有问题。所以我必须找到如何调用 do_read()

更新 3:如果我做websocket_session_ptr new_websocket(新 websocket_session(std::move(socket)));
acceptor.async_accept(
socket ,
升压::绑定(bind)(
&tcp_server::websocket_accept,
这,
boost::asio::placeholders::error,
new_websocket
));

引用:boost beast websocket example ,我首先接受套接字,然后在使用 m_ws.async_accept() 接受 websocket 之后,但我现在有 错误的文件描述符,这意味着套接字未打开。

P.S: 我更新了 ide URL(GDB 在线调试器)

最佳答案

您在构造函数内部使用指向 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() 尝试从 enable_shared_from_this 锁定单元化的 weak_ptr。正如您在 documentation 中看到的那样抛出 std::bad_weak_ptr 异常(广告 11)

shared_from_this 的文档明确警告不要这样做:

It is permitted to call shared_from_this only on a previously shared object, i.e. on an object managed by std::shared_ptr (in particular, shared_from_this cannot be called in a constructor).

关于c++ - bad_weak_ptr with boost 智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795539/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com