我需要关心async_write呼叫套接字的生命周期吗?

Do I need to care about socket's lifetime in call to async_write?

本文关键字:套接字 生命 周期 呼叫 write 关心 async      更新时间:2023-10-16

我用这种方式调用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)
    );
}

现在,在我的代码中,在对sendhandle_send的调用之间,我传递的套接字可能会被破坏,因为tcp_socket_pointer超出了它的作用域。

这合法吗?我的意思是,我需要确保引用的tcp::套接字在异步操作完成之前一直存在吗?我的直觉告诉我asio::async_write会立即进行系统调用,所以我不必担心,但我最好问:)。

如果它不能像我预期的那样工作,那么将tcp_socket_pointer作为参数传递给handle_send以确保它所指向的tcp::套接字不会过期是个好主意吗?

您可以使用它,但当tcp::socket被销毁时,async_*调用将被取消。

您可能希望将shared_ptr保留到套接字,并将其绑定到完成处理程序,以便它保留引用,这确实是您所描述的。