我这样调用asio :: async_write:
namespace asio = boost::asio;
using asio::ip::tcp;
using std::string;
shared_pointer<tcp::socket> tcp_socket_pointer;
string message;
...
void send() {
asio::async_write(
*tcp_socket_pointer,
asio::buffer(message),
boost::bind(
&handle_send, // defined elsewhere
asio::placeholders::error,
asio::placeholders::bytes_transferred)
);
}
现在,在我的代码中,有可能在调用send
和handle_send
我传递的套接字之间被破坏,因为tcp_socket_pointer
超出了范围。
合法吗 我的意思是,我是否需要确保引用的tcp :: socket一直持续到异步操作完成?我的直觉告诉我,asio :: async_write立即进行系统调用,因此我不必担心,但我最好问一下:)。
万一它不能按我期望的那样工作,将它tcp_socket_pointer
作为参数传递给它handle_send
,以确保它指向的tcp :: socket不会过期是个好主意吗?
您可以使用它,但是销毁销毁async_*
电话时,该电话将被取消tcp::socket
。
您可能要保留一个shared_ptr到套接字,并将其绑定到完成处理程序,以便它保留一个引用,这确实是您所描述的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句