我可以在两个不同的类实例中使用boost asio套接字引用吗

Can i have boost asio socket references in two different class instances?

本文关键字:实例 boost asio 引用 套接字 两个 我可以      更新时间:2023-10-16

我想std::move(my_asio_socket)到某个类的实例。如果我对其他类的一个实例也做同样的操作呢?

我的目的是在一个类实例(比如说类A)中执行read_async,在另一个类(比如说B)中执行write_async。由于某些功能实现,我应该这样做。

任何建议都很好。

更新

它没有像我预期的那样正常工作
VS2015(vc14编译器)在调试时向我显示了一种异常:

Microsoft C++ exception: boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> > at memory location 0x02D8E3BC.

当我在VS中点击continue后,它向我显示:

Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.

正如我所说,我正在尝试将套接字boost::move(或std::move)连接到其他类实例。以下是我正在做的事情的代码片段:

boost::shared_ptr<connection> new_connection_;//it's a field in my class,
//that's why i should reset it later
new_connection_.reset(new connection(std::move(socket_), io_service_));
new_connection_->start();

现在是我的connectionctor:

connection::connection(boost::asio::ip::tcp::socket sock, boost::asio::io_service& io_ptr)
: socket_(boost::move(sock)),
io_ptr_(io_ptr),
remote_ep(socket_.remote_endpoint()),
//request_handler_(new request_handler(boost::move(socket_))),
work(new boost::asio::io_service::work(io_ptr))
{
boost::shared_ptr<request_handler> req_ptr(new request_handler(boost::move(socket_)));
request_handler_.swap(req_ptr);
}

正如您所看到的,我已经尝试在注释行中进行初始化,但它显示了相同的结果
这是request_handler:的ctor

request_handler::request_handler(boost::asio::ip::tcp::socket sock):
socket_(boost::move(sock)){ }

这是我的方法connection::start,其中问题检测到:

void connection::start()
{
boost::asio::ip::tcp::socket::keep_alive kl(true);
boost::asio::ip::tcp::socket::enable_connection_aborted eca(true);
// here it breaks, when trying to set an option
socket_.set_option(eca);
socket_.set_option(kl);
socket_.async_read_some(boost::asio::buffer(buffer_),
boost::bind(&connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}

只有当我使用将socket移动到request_handler的新实例中时,才会出现此问题。如果我不是,那么一切都会好起来的。我不明白这可能是什么原因,但我的connection类的socket_(我到处声明它,没有任何&*)字段似乎丢失了。但是调试器没有向我显示类似null的smthing,所以我不知道它是什么。

一般情况下不保证:

Move赋值运算符通常会"窃取"参数所拥有的资源(例如,指向动态分配对象、文件描述符、TCP套接字、I/O流、运行线程等的指针),而不是复制它们,并使参数处于某种有效但不确定的状态。例如,从std::字符串或std::向量进行移动赋值可能会导致参数为空。然而,这种行为不应被依赖。

但根据tcp::socket的文档,它处于相同的状态:

移动后,moved-from对象的状态与使用basic_stream_socket(io_service&)构造函数构造时的状态相同。