C ++ Boost.Asio对象生命周期

时间:2014-01-07 04:07:20

标签: c++ boost-asio

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

Socket的析构函数应该关闭套接字。但异步后端可以处理这个吗?它会取消异步操作并调用处理程序吗?可能不是吗?

2 个答案:

答案 0 :(得分:4)

当套接字被销毁时,它的服务为invokes destroy。当调用SocketService的destroy()函数时,它通过调用非投掷close()来取消异步操作。取消操作的处理程序将在io_service内发布,并发出boost::asio::error::operation_aborted错误。


以下是演示记录行为的完整示例:

#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();
}

及其输出:

handle_connect: Operation canceled

答案 1 :(得分:0)

为什么要使用new创建套接字?它绝对不会做正常的过程。 如果您真的想使用new创建socket,则必须在程序结束时关闭并删除。

以下是一个示例。

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();