enable_shared_from_this.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #ifndef BOOST_SMART_PTR_ENABLE_SHARED_FROM_THIS_HPP_INCLUDED
  2. #define BOOST_SMART_PTR_ENABLE_SHARED_FROM_THIS_HPP_INCLUDED
  3. //
  4. // enable_shared_from_this.hpp
  5. //
  6. // Copyright 2002, 2009 Peter Dimov
  7. //
  8. // Distributed under the Boost Software License, Version 1.0.
  9. // See accompanying file LICENSE_1_0.txt or copy at
  10. // http://www.boost.org/LICENSE_1_0.txt
  11. //
  12. // http://www.boost.org/libs/smart_ptr/enable_shared_from_this.html
  13. //
  14. #include <boost/smart_ptr/weak_ptr.hpp>
  15. #include <boost/smart_ptr/shared_ptr.hpp>
  16. #include <boost/assert.hpp>
  17. #include <boost/config.hpp>
  18. namespace boost
  19. {
  20. template<class T> class enable_shared_from_this
  21. {
  22. protected:
  23. enable_shared_from_this()
  24. {
  25. }
  26. enable_shared_from_this(enable_shared_from_this const &)
  27. {
  28. }
  29. enable_shared_from_this & operator=(enable_shared_from_this const &)
  30. {
  31. return *this;
  32. }
  33. ~enable_shared_from_this()
  34. {
  35. }
  36. public:
  37. shared_ptr<T> shared_from_this()
  38. {
  39. shared_ptr<T> p( weak_this_ );
  40. BOOST_ASSERT( p.get() == this );
  41. return p;
  42. }
  43. shared_ptr<T const> shared_from_this() const
  44. {
  45. shared_ptr<T const> p( weak_this_ );
  46. BOOST_ASSERT( p.get() == this );
  47. return p;
  48. }
  49. public: // actually private, but avoids compiler template friendship issues
  50. // Note: invoked automatically by shared_ptr; do not call
  51. template<class X, class Y> void _internal_accept_owner( shared_ptr<X> const * ppx, Y * py ) const
  52. {
  53. if( weak_this_.expired() )
  54. {
  55. weak_this_ = shared_ptr<T>( *ppx, py );
  56. }
  57. }
  58. private:
  59. mutable weak_ptr<T> weak_this_;
  60. };
  61. } // namespace boost
  62. #endif // #ifndef BOOST_SMART_PTR_ENABLE_SHARED_FROM_THIS_HPP_INCLUDED