c++ - 使用 boost::asio::io_service 作为类成员字段

标签 c++ boost boost-asio

我在类里面使用 boost asio 库:

标题:

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;

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

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

最佳答案

io_service不可复制。

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

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

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

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

关于c++ - 使用 boost::asio::io_service 作为类成员字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29623652/

相关文章:

c++ - boost 测试是否支持宽字符串?

c++ - 随机访问(或以其他方式快速访问)boost 图形库中的边

c++ - Boost 库 - 只构建我需要的东西

C++ 提升 asio async_read 与同时使用两个线程

C++ 函数 : invalid initialization of non-const reference of type

c++ - 在类构造函数中动态分配内存

C++ : Declaring struct return-type function in header file

c++ - 在 boost::bind 中使用已删除的函数

c++ - boost::asio::async_read_until 问题

c++ - 3D 图像中的连通分量及其索引