5

这是我的 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)时,程序会出现段错误,而不是很好地关闭。我花了最后半个小时看这个,但我根本不明白为什么这会出现段错误,你们中的任何人都可以发现这个问题吗?

4

1 回答 1

10

我想我发现了这个问题。注意成员的声明顺序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;
}

声明connectionio_service解决问题。

该死

于 2013-08-02T05:22:56.600 回答