本文介绍了使用boost :: asio :: io_service作为类成员字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有类使用boost asio库:
标题:
class TestIOService {
public:
void makeConnection();
static TestIOService getInst();
private:
TestIOService(std :: string address);
std :: string address;
// boost :: asio :: io_service服务;
};
Impl:
code> #include< boost / asio / ip / address.hpp>
#include< boost / asio / ip / udp.hpp>
#includeTestIOService.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服务;
没有问题,但是当我有它作为类字段成员(注释掉代码)得到这个错误:
解决方案 io_service
不可复制。
您可以将其包装在 shared_ptr< io_service>
如果您的课程需要可复制,则逻辑上不会 >包含 io_service
对象
例如下面的示例确实创建了两个不共享连接的测试类实例:
#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();
}
这篇关于使用boost :: asio :: io_service作为类成员字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!