1 #ifndef BOOST_ENABLE_SHARED_FROM_THIS2_HPP_INCLUDED
2 #define BOOST_ENABLE_SHARED_FROM_THIS2_HPP_INCLUDED
5 // enable_shared_from_this2.hpp
7 // Copyright 2002, 2009 Peter Dimov
8 // Copyright 2008 Frank Mori Hess
10 // Distributed under the Boost Software License, Version 1.0.
11 // See accompanying file LICENSE_1_0.txt or copy at
12 // http://www.boost.org/LICENSE_1_0.txt
15 #include <boost/config.hpp>
16 #include <boost/shared_ptr.hpp>
17 #include <boost/assert.hpp>
18 #include <boost/detail/workaround.hpp>
26 class esft2_deleter_wrapper
30 shared_ptr<void> deleter_;
34 esft2_deleter_wrapper()
38 template< class T > void set_deleter( shared_ptr<T> const & deleter )
43 template< class T> void operator()( T* )
45 BOOST_ASSERT( deleter_.use_count() <= 1 );
52 template< class T > class enable_shared_from_this2
56 enable_shared_from_this2()
60 enable_shared_from_this2( enable_shared_from_this2 const & )
64 enable_shared_from_this2 & operator=( enable_shared_from_this2 const & )
69 ~enable_shared_from_this2()
71 BOOST_ASSERT( shared_this_.use_count() <= 1 ); // make sure no dangling shared_ptr objects exist
76 mutable weak_ptr<T> weak_this_;
77 mutable shared_ptr<T> shared_this_;
81 shared_ptr<T> shared_from_this()
84 return shared_ptr<T>( weak_this_ );
87 shared_ptr<T const> shared_from_this() const
90 return shared_ptr<T>( weak_this_ );
95 void init_weak_once() const
97 if( weak_this_._empty() )
99 shared_this_.reset( static_cast< T* >( 0 ), detail::esft2_deleter_wrapper() );
100 weak_this_ = shared_this_;
104 public: // actually private, but avoids compiler template friendship issues
106 // Note: invoked automatically by shared_ptr; do not call
107 template<class X, class Y> void _internal_accept_owner( shared_ptr<X> * ppx, Y * py ) const
109 BOOST_ASSERT( ppx != 0 );
111 if( weak_this_.use_count() == 0 )
113 weak_this_ = shared_ptr<T>( *ppx, py );
115 else if( shared_this_.use_count() != 0 )
117 BOOST_ASSERT( ppx->unique() ); // no weak_ptrs should exist either, but there's no way to check that
119 detail::esft2_deleter_wrapper * pd = boost::get_deleter<detail::esft2_deleter_wrapper>( shared_this_ );
120 BOOST_ASSERT( pd != 0 );
122 pd->set_deleter( *ppx );
124 ppx->reset( shared_this_, ppx->get() );
125 shared_this_.reset();
132 #endif // #ifndef BOOST_ENABLE_SHARED_FROM_THIS2_HPP_INCLUDED