boost :: make_shared失败但std :: make_shared工作

时间:2018-05-13 03:11:05

标签: c++ boost-asio make-shared

我在boost :: asio中做了一个echo-server示例。但是使用boost :: make_shard会导致"未知异常"虽然std :: make_shared不会。请参阅注释行。

我正在使用视觉工作室2017并提升1.67。评论的部分将崩溃,而未注释的部分将不会。似乎boost lib在boost / stage / lib中符合vs141。

#include <iostream>
#include <boost/asio.hpp>
#include <boost/make_shared.hpp>
using boost::asio::ip::tcp;
using std::cout;
using std::endl;
using std::size_t;

class session :public std::enable_shared_from_this<session> {
public:
    session(tcp::socket socket) :socket_(std::move(socket)) {
    }
    void start() {
        do_read();
    }
private:

    void do_read() {
        auto self(shared_from_this());
        socket_.async_read_some(boost::asio::buffer(buffer_, maxlen),
            [this, self](boost::system::error_code error, size_t read_len) {
            if (!error) {
                do_write(read_len);
            }
            else {
                cout << error.message() << endl;
            }
        });
    }
    void do_write(size_t len_write) {
        auto self(shared_from_this());
        boost::asio::async_write(socket_, boost::asio::buffer(buffer_, len_write),
            [this, self](boost::system::error_code error, size_t byte_transferred) {
            if (!error) {
                do_read();
            }
            else {
                cout << "error 3,only " << byte_transferred << " bytes writen" << endl;
            }
        });
    }
    tcp::socket socket_;
    enum { maxlen = 1024 };
    char buffer_[maxlen];
};


class server {
public:
    server(boost::asio::io_context& io_context, short port)
        :acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) {
        start();
    }

    void start() {


        acceptor_.async_accept(
            [this](boost::system::error_code ec, tcp::socket socket)
        {
            if (!ec)
            {
                std::make_shared<session>(std::move(socket))->start();
        //      boost::make_shared<session>(std::move(socket))->start();

            }

            start();
        });
    }
private:
    tcp::acceptor acceptor_;
};

int main(int argc, char **argv) {
    if (argc != 2) {
        cout << "usage: server.exe  Port" << endl;
    }
    try {
        boost::asio::io_context io_context;
        server server(io_context, std::atoi(argv[1]));
        io_context.run();
    }
    catch (std::exception e) {
        cout << e.what() << endl;
    }
}

1 个答案:

答案 0 :(得分:1)

何时使用boost共享指针

boost::make_shared<session>(std::move(socket))->start();

您必须从boost适配器类继承您的类,如下所示:

class session :public boost::enable_shared_from_this<session> {