async_resolve and async_connect params lifetime

旧时模样 提交于 2019-12-06 14:50:25

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 a shard_ptr and bind a copy of the shared_ptr into the handler.
  • For async_resolve the query object is passed by const-reference and eventually copied in the underlying operation's constructor (resolve_endpoint_op). This also permits using a temporary query object as well.

    {
      typedef boost::asio::ip::tcp::resolver::query query;
      resolver_.async_resolve(query(host_, port_), );
    }
    
  • async_resolve expects 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 resolver does not need to remain alive because the iterator's have shared ownership of the query results. While not in the documentation, the ip::basic_resolver_iterator maintains a shared_ptr to a std::vector of ip::basic_resolver_entry objects. The basic_resolver_entry objects have member variables for endpoint, host name, and service name.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!