mardi 31 juillet 2018

Why can this boost::asio::tcp::socket be re-used?

Below is some code from a boost::asio example. Why is it okay to move the socket_ member when constructing a chat_session if the recursive call at the bottom of the handler is going to hand this same tcp::socket out next time an accept happens? I thought that after a move operation, an object was no longer safe to use.

class chat_server
{
public:
  chat_server(boost::asio::io_service& io_service,
      const tcp::endpoint& endpoint)
    : acceptor_(io_service, endpoint),
      socket_(io_service)
  {
    do_accept();
  }

private:
  void do_accept()
  {
    acceptor_.async_accept(socket_,
        [this](boost::system::error_code ec)
        {
          if (!ec)
          {
            std::make_shared<chat_session>(std::move(socket_), room_)->start();
          }

          do_accept();
        });
  }

  tcp::acceptor acceptor_;
  tcp::socket socket_;
  chat_room room_;
};

Aucun commentaire:

Enregistrer un commentaire