2015-04-14 55 views
1

我有课,我用升压ASIO库:使用boost :: ASIO :: io_service对象的类成员场

页眉:

class TestIOService { 

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

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

默认地将Impl:

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

当我有服务定义d中的makeConnection方法这一行:

boost::asio::io_service service; 

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

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

回答

3

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

谢谢回答,我不是很熟练的在C++中,但有关的设计,我应该创建新为每个新请求提供io_service服务? – Joe

+0

只要您每次都调用'getInst()',共享指针就会执行。虽然复制类不会创建一个新的io_service,但是(请注意,'getInst()'_returning_试图复制(或移动)类) – sehe

+0

@Joe扩展了一个有用的(?)示例* [Live On Coliru]( http://coliru.stacked-crooked.com/a/f219f1396a36cae8)* – sehe

相关问题