使用 boost::asio::io_service 作为 class 成员字段

Using boost::asio::io_service as class member field

我有 class 我使用 boost asio 库的地方:

Header:

class TestIOService {

public:
    void makeConnection();
    static TestIOService getInst();

private:
    TestIOService(std::string address);
    std::string address;
    // boost::asio::io_service service;
};

实现:

#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/udp.hpp>
#include "TestIOService.h"

void TestIOService::makeConnection() {
    boost::asio::io_service service;
    boost::asio::ip::udp::socket socket(service);
    boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address::from_string("192.168.1.2"), 1234);
    socket.connect(endpoint);
    socket.close();
}

TestIOService::TestIOService(std::string address) : address(address) { }

TestIOService TestIOService::getInst() {
    return TestIOService("192.168.1.2");
}

和主要的:

int main(void)
{
    TestIOService service = TestIOService::getInst();
    service.makeConnection();
}

当我使用以下行在 makeConnection 方法中定义服务时:

boost::asio::io_service service;

没有问题,但是当我把它作为 class 字段成员时(在代码中注释掉)我得到这个错误:

note: ‘TestIOService::TestIOService(TestIOService&&)’ is implicitly deleted because the default definition would be ill-formed: class TestIOService {

io_service不可复制。

您可以通过将其包装在 shared_ptr<io_service> 中使其快速共享,但您真的应该先重新考虑设计。

如果您的class需要可复制,逻辑上包含io_service对象

例如以下示例确实创建了两个不共享连接的测试实例 class:

Live On Coliru

#include <boost/asio.hpp>
#include <boost/make_shared.hpp>
#include <iostream>

class TestIOService {

public:
    void makeConnection();
    static TestIOService getInst();

private:
    TestIOService(std::string address);
    std::string address;

    boost::shared_ptr<boost::asio::ip::udp::socket> socket;
    boost::shared_ptr<boost::asio::io_service> service;
};

void TestIOService::makeConnection() {
    using namespace boost::asio;
    service = boost::make_shared<io_service>();
    socket  = boost::make_shared<ip::udp::socket>(*service);
    socket->connect({ip::address::from_string("192.168.1.2"), 1234 });
    //socket->close();
}

TestIOService::TestIOService(std::string address) 
    : address(address) { }

TestIOService TestIOService::getInst() {
    return TestIOService("192.168.1.2");
}

int main() {
    auto test1 = TestIOService::getInst();
    auto test2 = TestIOService::getInst();
}