Boost.Asio segfault,不明白为什么

时间:2013-08-02 05:07:21

标签: c++ segmentation-fault boost-asio

这是基于示例的Boost.Asio项目中的SSCCE。我花了大约一个小时的时间跟踪这个错误:

#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)时,程序会出现段错误,而不是很好地关闭。我花了半个小时的时间看着这个,但我根本不明白为什么会出现这种错误,你们有没有人能发现这个问题?

1 个答案:

答案 0 :(得分:8)

我想我发现了这个问题。请注意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的引用,该引用已被销毁。

事实上,这几乎就是发生的事情,并导致了一个段错误:

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;
}

connection解决问题后声明io_service

<子>该死