The role and implementation principle of the C++ boost library ---- share_from_this class

Original link:

When using the boost library, you often see the following classes

class A:public enable_share_from_this<A>

Under what circumstances should class A inherit enable_share_from_this?

Usage situation : When class A is managed by share_ptr, and the member function of class A needs to pass the current class object as a parameter to other functions, it needs to pass a share_ptr pointing to itself.

We make class A inherit enable_share_from_this, and then return the share_ptr that points to itself through its member function share_from_this().

There are 2 doubts above:

1. Why pass share_ptr when passing the current class object as a parameter to other functions? Can't pass the this pointer directly?

A raw pointer is passed to the caller, who does not know what the caller will do? If the caller deletes the object, and share_tr still points to the object at this time.

2. Is it OK to pass share_ptr like this? share_ptr<this>

This will cause 2 non-shared share_ptr to point to an object, and finally cause 2 destructors of the object.

A very typical example in boost official documentation: http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/tutorial/tutdaytime3/src.html

Part of the code:

copy code
 1 class tcp_connection
 2   : public boost::enable_shared_from_this<tcp_connection>
 3 {
 4 public:
 5   typedef boost::shared_ptr<tcp_connection> pointer;
 6 
 7   static pointer create(boost::asio::io_service& io_service)
 8   {
 9     return pointer(new tcp_connection(io_service));
10   }
11 
12   tcp::socket& socket()
13   {
14     return socket_;
15   }
16 
17   void start()
18   {
19     message_ = make_daytime_string();
20 
21     boost::asio::async_write(socket_, boost::asio::buffer(message_),
22         boost::bind(&tcp_connection::handle_write, shared_from_this(),
23           boost::asio::placeholders::error,
24           boost::asio::placeholders::bytes_transferred));
25   }
26 
27 private:
28   tcp_connection(boost::asio::io_service& io_service)
29     : socket_(io_service)
30   {
31   }
32 
33   void handle_write(const boost::system::error_code& /*error*/,
34       size_t /*bytes_transferred*/)
35   {
36   }
37 
38   tcp::socket socket_;
39   std::string message_;
40 };
copy code

The class tcp_connection inherits enable_share_from_this. In line 22, its member function start() returns a share_ptr pointing to itself through share_from_this.

Implementation principle:

How does share_from_this() return a share_ptr pointing to this object? Apparently it cannot return share_ptr<this> directly. Because the share_ptr it returns must be shared with the share_ptr that manages the object, that is to say, the reference count of the returned share_ptr is the same as the reference count of the share_ptr that manages the object. In fact, enable_share_from_this stores the reference count of the share_ptr that manages the object, which is implemented by weak_ptr. In enable_share_from_this, there is a member weak_this_.

But now the question is: when to initialize this weak_ptr? Because the class object has not yet generated the corresponding shared_ptr used to manage this object. In fact, this weak_ptr is initialized through the constructor of share_ptr.

shared_ptr defines the following constructor:
1  template<class Y>
2 explicit shared_ptr( Y * p ): px( p ), pn() // Y must be complete
3 {
4   boost::detail::sp_pointer_construct( this, p, pn );
5 }
which calls boost::detail::sp_pointer_construct 
copy code
1 template< class T, class Y > inline void sp_pointer_construct( boost::shared_ptr< T > * ppx, Y * p, boost::detail::shared_count & pn )
2 {
3    boost::detail::shared_count( p ).swap( pn );
4    boost::detail::sp_enable_shared_from_this( ppx, p, p );
5 }
copy code
 It calls boost::detail::sp_enable_shared_from_this again
 
share_ptr has 2 overloaded functions
copy code
1 template< class X, class Y, class T > inline void sp_enable_shared_from_this( boost::shared_ptr<X> const * ppx, Y const * py, boost::enable_shared_from_this< T > const * pe )
2 {
3   if( pe != 0 )
4  {
5    pe->_internal_accept_owner( ppx, const_cast< Y* >( py ) );
6  }
7 }
copy code
1 inline void sp_enable_shared_from_this( ... )
2 {
3 }

Since our class inherits enable_share_from_this, the former is called

It calls _internal_accept_owner of enable_shared_from_this again:
copy code
template<class X, class Y> void _internal_accept_owner( shared_ptr<X> const * ppx, Y * py ) const
{
  if( weak_this_.expired() )
  {
    weak_this_ = shared_ptr<T>( *ppx, py );
  }
}
copy code

Finally, the copy assignment is made to the weak_this_ member of enable_shared_from_this, so that the entire weak_ptr is used as an observer of the class object shared_ptr. When calling share_from_this(), it can be generated from this weak_ptr, and the reference count is the same.

copy code
1 shared_ptr<T const> shared_from_this() const
2 {
3  shared_ptr<T const> p( weak_this_ );
4  BOOST_ASSERT( p.get() == this );
5  return p;
6 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325981093&siteId=291194637