00001 #ifndef BOOST_SMART_PTR_ENABLE_SHARED_FROM_THIS_HPP_INCLUDED 00002 #define BOOST_SMART_PTR_ENABLE_SHARED_FROM_THIS_HPP_INCLUDED 00003 00004 // 00005 // enable_shared_from_this.hpp 00006 // 00007 // Copyright 2002, 2009 Peter Dimov 00008 // 00009 // Distributed under the Boost Software License, Version 1.0. 00010 // See accompanying file LICENSE_1_0.txt or copy at 00011 // http://www.boost.org/LICENSE_1_0.txt 00012 // 00013 // http://www.boost.org/libs/smart_ptr/enable_shared_from_this.html 00014 // 00015 00016 #include <boost/smart_ptr/weak_ptr.hpp> 00017 #include <boost/smart_ptr/shared_ptr.hpp> 00018 #include <boost/assert.hpp> 00019 #include <boost/config.hpp> 00020 00021 namespace boost 00022 { 00023 00024 template<class T> class enable_shared_from_this 00025 { 00026 protected: 00027 00028 enable_shared_from_this() 00029 { 00030 } 00031 00032 enable_shared_from_this(enable_shared_from_this const &) 00033 { 00034 } 00035 00036 enable_shared_from_this & operator=(enable_shared_from_this const &) 00037 { 00038 return *this; 00039 } 00040 00041 ~enable_shared_from_this() 00042 { 00043 } 00044 00045 public: 00046 00047 shared_ptr<T> shared_from_this() 00048 { 00049 shared_ptr<T> p( weak_this_ ); 00050 BOOST_ASSERT( p.get() == this ); 00051 return p; 00052 } 00053 00054 shared_ptr<T const> shared_from_this() const 00055 { 00056 shared_ptr<T const> p( weak_this_ ); 00057 BOOST_ASSERT( p.get() == this ); 00058 return p; 00059 } 00060 00061 public: // actually private, but avoids compiler template friendship issues 00062 00063 // Note: invoked automatically by shared_ptr; do not call 00064 template<class X, class Y> void _internal_accept_owner( shared_ptr<X> const * ppx, Y * py ) const 00065 { 00066 if( weak_this_.expired() ) 00067 { 00068 weak_this_ = shared_ptr<T>( *ppx, py ); 00069 } 00070 } 00071 00072 private: 00073 00074 mutable weak_ptr<T> weak_this_; 00075 }; 00076 00077 } // namespace boost 00078 00079 #endif // #ifndef BOOST_SMART_PTR_ENABLE_SHARED_FROM_THIS_HPP_INCLUDED