简体   繁体   中英

Use case of shared_from_this and this

In this source file there are two classes : tcp_connection and tcp_server . I've seleceted the relevant bits of code in my opinion but you might want to refer to the full source code for more information.

class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
  typedef boost::shared_ptr<tcp_connection> pointer;

  void start()
  {
    message_ = make_daytime_string();

    boost::asio::async_write(socket_, boost::asio::buffer(message_),
        boost::bind(&tcp_connection::handle_write, shared_from_this()));
  }
};

class tcp_server
{    
private:
  void start_accept()
  {
    tcp_connection::pointer new_connection =
      tcp_connection::create(acceptor_.get_io_service());

    acceptor_.async_accept(new_connection->socket(),
        boost::bind(&tcp_server::handle_accept, this, new_connection,
          boost::asio::placeholders::error));
  }
};

My question is simple : what would we use shared_from_this as a bind argument within the async_write function and use this as a bind argument within the async_accept function?

Shared pointers govern the lifetime of a dynamically allocated object. Each held pointer increases a reference count and when all held pointers are gone the referred to object is freed.

The Server

There's only one server, and it's not dynamically allocated. Instead, the instance lives longer than the acceptor (and possibly the io_service) so no all async operations can trust the object to stay alive long enough.

The Connections

Each client spawns a new connection, dynamically allocating (make_shared) a tcp_connection instance, and then starting asynchronous operations on it.

The server does not keep a copy of the shared-pointer, so when all async operations on the connection complete (eg because the connection was dropped) the tcp_connection object will be freed.

However because the object must not be destroyed when an async operation is in progress, you need to bind the completion handler to the shared pointer ( shared_from_this ) instead of this .

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