I would like to know what is lifetime of objects passed to mentioned methods.
async_resolve
ip::basic_resolver::async_resolve(const query & q, ResolveHandler handler);
(1) Do I need to keep resolver alive until handler is called? (yes)
(2) Does async_resolve copy query object? (I am passing one created on the stack – yes)
{
boost::asio::ip::tcp::resolver::query query(host_, port_);
resolver_.async_resolve(query, );
}
(3) Is boost::asio::ip::tcp::resolver::iterator returned in handler by value? (yes)
async_connect
template<..> void async_connect(basic_socket<Protocol, SocketService> & s,
Iterator begin, ComposedConnectHandler h);
(4) Is begin passed by value? (yes)
(5) Do I need to keep resolver alive? (no)
With Boost.Asio, the general rule is that:
When there are exceptions to the rule, the documentation will indicate it, such as the case of the buffers argument for
boost::asio::async_write, which must remain valid until the handler is called.For
ip::basic_resolver:boost::asio::error::operation_aborted. If you do not want to manage the lifespan of the service object, then manage it with ashard_ptrand bind a copy of theshared_ptrinto the handler.For
async_resolvethequeryobject is passed by const-reference and eventually copied in the underlying operation’s constructor (resolve_endpoint_op). This also permits using a temporaryqueryobject as well.async_resolveexpects handler to meet the ResolverHandler requirements. It documents that the iterator argument is taken by value.For
boost::asio::async_connect:resolverdoes not need to remain alive because the iterator’s have shared ownership of the query results. While not in the documentation, theip::basic_resolver_iteratormaintains ashared_ptrto astd::vectorofip::basic_resolver_entryobjects. Thebasic_resolver_entryobjects have member variables for endpoint, host name, and service name.