Boost logo

Boost Users :

Subject: [Boost-users] enable_shared_from_this2
From: Peter Soetens (peter.soetens_at_[hidden])
Date: 2011-02-17 06:55:50


Hi list,

I was in the need for a shared_from_this() in my constructor, so I chose this
implementation for my class. Apart from the header being
there and one mailing list thread, there's nothing that points to the
existence of this header.

Since we want to keep compatibility with Boost 1.38, I tried to backport the
enable_shared_from_this2 class to that version. I was
wondering why the weak_ptr::_empty() method was added to the weak_ptr API and
why weak_ptr::expired() was not used instead ? I tried
to emulate the same behavior by adding a 'bool' to the
enable_shared_from_this2 class. Which works for my tests, but is there a
pitfall to
that solution ? Could I just replace this logic with weak_this_.expired() ?

diff --git a/rtt/internal/enable_shared_from_this2.hpp
b/rtt/internal/enable_shared_from_this2.hpp
index a5bfcff..cb659f0 100644
--- a/rtt/internal/enable_shared_from_this2.hpp
+++ b/rtt/internal/enable_shared_from_this2.hpp
@@ -53,11 +53,13 @@ template< class T > class enable_shared_from_this2
 {
 protected:
 
- enable_shared_from_this2()
+ enable_shared_from_this2() : weak_init(false)
     {
     }
 
- enable_shared_from_this2( enable_shared_from_this2 const & )
+ // note: the copy constructor and operator= don't do anything, ie, they
don't copy
+ // refcount status from the other object.
+ enable_shared_from_this2( enable_shared_from_this2 const & ) :
weak_init(false)
     {
     }
 
@@ -75,6 +77,7 @@ private:
 
     mutable weak_ptr<T> weak_this_;
     mutable shared_ptr<T> shared_this_;
+ mutable bool weak_init; // we deviate from the boost 1.40 implementation
because weak_this_._empty() is not available in older
versions.
 
 public:
 
@@ -94,10 +97,11 @@ private:
 
     void init_weak_once() const
     {
- if( weak_this_._empty() )
+ if( !weak_init )
         {
             shared_this_.reset( static_cast< T* >( 0 ),
detail::esft2_deleter_wrapper() );
             weak_this_ = shared_this_;
+ weak_init = true;
         }
     }
 
@@ -111,6 +115,7 @@ public: // actually private, but avoids compiler template
friendship issues
         if( weak_this_.use_count() == 0 )
         {
             weak_this_ = shared_ptr<T>( *ppx, py );
+ weak_init = true;
         }
         else if( shared_this_.use_count() != 0 )
         {

Thanks for any feedback,
Peter


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net