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:
- Arguments passed by const-reference or value are copied. If supported, they may be moved.
- Arguments passed by non-const-reference are required to remain valid until the synchronous operation completes or until the asynchronous operation's handler is called.
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:
- As with other service objects, if the service object is destroyed with outstanding asynchronous operations, then the asynchronous operation handlers will be invoked with
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.{ typedef boost::asio::ip::tcp::resolver::query query; resolver_.async_resolve(query(host_, port_), ); }async_resolveexpects handler to meet the ResolverHandler requirements. It documents that the iterator argument is taken by value.
For boost::asio::async_connect:
- Per the documentation, the begin argument is passed by value.
- The
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.
来源:https://stackoverflow.com/questions/12799720/async-resolve-and-async-connect-params-lifetime