Boost logo

Boost :

From: Gavin Lambert (boost_at_[hidden])
Date: 2019-07-15 23:36:05


On 16/07/2019 00:35, JH wrote:
> I use boost TCP socket for months, it works well until I call a
> termination of smart pointer which is running at
> boost::asio::async_read. Could anyone explain what could be the cause
> for the following errors?

Be careful of the order of operations when you have pending async actions.

In particular, when you close a socket, the async read will be cancelled
and a cancellation callback will be queued to the io_context -- but you
must still guarantee that all of the objects involved in the callback
for that operation (including the socket and the read buffer, plus
anything else accessed by the completion handler) are still kept alive
until the callback actually executes.

A simple trick to help ensure this (as demonstrated in several of the
Asio examples) is to pass a shared_ptr to the container of the socket
and read buffer to the async_read operation (eg. as a bound lambda
argument); this will keep that object and its children alive until the
handler is actually called.

Of course, then you can't use destruction of that object to trigger the
close in the first place, which can have consequences for the rest of
your app. There are some ways around this, such as separating the
"real" container of the socket/buffer from the "logical" container from
the perspective of the rest of the app.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk