kitek
kitek

Reputation: 117

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

I'm calling asio::async_write this way:

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)
    );
}

Now, in my code it is possible that between calls to send and handle_send the socket I pass gets destroyed because tcp_socket_pointer goes out of it's scope.

Is it legal? I mean, do I need to ensure that the referenced tcp::socket persists until the asynchronous operation completes? My intuition tells me that asio::async_write makes a system call immediately so I wouldn't need to worry, but I better ask :).

In case it doesn't work as I'm expecting, is it a good idea to pass tcp_socket_pointer as an argument to handle_send in order to make sure that tcp::socket it points to doesn't expire?

Upvotes: 1

Views: 329

Answers (1)

sehe
sehe

Reputation: 393134

You can use this, but the async_* call will be canceled when the tcp::socket is destroyed.

You may want to keep a shared_ptr to the socket and bind it to the completion handler so it keeps a reference, which is indeed what you describe.

Upvotes: 4

Related Questions