我有使用boost asio库的课程:
部首:
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();
}
当我使用此行在makeConnection方法中定义服务时:
boost::asio::io_service service;
没有问题,但当我将它作为类字段成员(在代码中注释掉)时,我收到此错误:
注意:'TestIOService :: TestIOService(TestIOService&amp;&amp;)'是隐含的 删除,因为默认定义不正确: class TestIOService {
答案 0 :(得分:3)
io_service
无法复制。
您可以将其包装在shared_ptr<io_service>
中快速分享,但您应该首先重新考虑设计。
如果您的类需要可复制,那么逻辑上不包含io_service
对象
E.g。以下示例确实创建了两个不共享连接的测试类实例:
<强> 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();
}