简体   繁体   中英

C++ Boost.Asio object lifetimes

asio::io_service ioService;
asio::ip::tcp::socket* socket = new asio::ip::tcp::socket(ioService);
socket->async_connect(endpoint, handler);
delete socket;

Socket's destructor should close the socket. But can the asynchronous backend handle this? Will it cancel the asynchronous operation and calling the handler? Probably not?

When the socket is destroyed, it invokes destroy on its service. When a SocketService's destroy() function is invoked, it cancels asynchronous operations by calling a non-throwing close() . Handlers for cancelled operations will be posted for invocation within io_service with a boost::asio::error::operation_aborted error.


Here is a complete example demonstrating the documented behavior:

#include <iostream>
#include <boost/asio.hpp>

void handle_connect(const boost::system::error_code& error)
{
  std::cout << "handle_connect: " << error.message() << std::endl;
}

int main()
{
  namespace ip = boost::asio::ip;
  using ip::tcp;

  boost::asio::io_service io_service;
  // Create socket with a scoped life.
  {
    tcp::socket socket(io_service);
    socket.async_connect(
        tcp::endpoint(ip::address::from_string("1.2.3.4"), 12345),
        &handle_connect);
  }
  io_service.run();
}

And its output:

handle_connect: Operation canceled

Why did you create the socket using new ? It won't definitely do normal process. If you really want to create the socket using new, you have to close and delete at the end of your program.

Here is a sample, just.

io_service service_;

ip::tcp::socket sock(service_);
sock.async_connect(ep, connect_handler);

deadline_timer t(service_, boost::posix_time::seconds(5));
t.async_wait(timeout_handler);

service_.run();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM