Boost.Asio segfault, no idea why(Boost.Asio 段错误,不知道为什么)
问题描述
这是我的 Boost.Asio 项目基于示例的 SSCCE.我花了大约一个小时来跟踪这个错误:
This is a SSCCE from my Boost.Asio project based on the examples. It took me about an hour to track the bug down to this:
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
class Connection {
public:
Connection(boost::asio::io_service& io_service) : socket(io_service) {}
private:
boost::asio::ip::tcp::socket socket;
};
class Server {
public:
Server() : signal_monitor(io_service) {
signal_monitor.add(SIGINT);
signal_monitor.add(SIGTERM);
signal_monitor.async_wait(
boost::bind(&Server::handle_signal_caught, this)
);
}
void run() {
// comment out the next line and there's no segfault
connection.reset(new Connection(io_service));
io_service.run();
}
private:
void handle_signal_caught() {
io_service.stop();
}
boost::shared_ptr<Connection> connection;
boost::asio::io_service io_service;
boost::asio::signal_set signal_monitor;
};
int main(int argc, char **argv) {
Server server;
server.run();
return 0;
}
当我发送信号 (ctrl+C) 时,程序会出现段错误,而不是很好地关闭.我已经花了最后半个小时看这个,但我根本不明白为什么这会出现段错误,你们中的任何人都可以发现这个问题吗?
When I send a signal (ctrl+C) the program segfaults instead of shutting down nicely. I've spent the last half hour looking at this, but I simply do not see why this would segfault, can any of you guys spot the issue?
推荐答案
我想我找到了问题所在.注意Server
成员的声明顺序:
I think I found out the issue. Note the declaration order of the members of Server
:
boost::shared_ptr<Connection> connection;
boost::asio::io_service io_service;
boost::asio::signal_set signal_monitor;
销毁顺序与声明顺序相反.这意味着首先 signal_monitor
,然后是 io_service
,最后是 connection
被破坏.但是 connection
包含一个 boost::asio::ip::tcp::socket
包含对 io_service
的引用,该引用已被破坏.
Destruction order is done in the opposite order of declaration. This means that first signal_monitor
, then io_service
and finally connection
get destroyed. But connection
contains a boost::asio::ip::tcp::socket
containing a reference to io_service
, which got destroyed.
事实上,这几乎就是正在发生的事情,并且也会导致段错误:
And indeed, this is pretty much what happening, and causes a segfault too:
int main(int argc, char **argv) {
auto io_service = new boost::asio::io_service();
auto socket = new boost::asio::ip::tcp::socket(*io_service);
delete io_service;
delete socket;
return 0;
}
在 io_service
解决问题后声明 connection
.
Declaring connection
after io_service
solves the issue.
该死的
这篇关于Boost.Asio 段错误,不知道为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Boost.Asio 段错误,不知道为什么


- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01