enable_shared_from_this.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. // See http://www.boost.org/libs/smart_ptr/ for documentation.
  13. //
  14. #include <boost/smart_ptr/weak_ptr.hpp>
  15. #include <boost/smart_ptr/shared_ptr.hpp>
  16. #include <boost/smart_ptr/detail/sp_noexcept.hpp>
  17. #include <boost/assert.hpp>
  18. #include <boost/config.hpp>
  19. namespace boost
  20. {
  21. template<class T> class enable_shared_from_this
  22. {
  23. protected:
  24. BOOST_CONSTEXPR enable_shared_from_this() BOOST_SP_NOEXCEPT
  25. {
  26. }
  27. BOOST_CONSTEXPR enable_shared_from_this(enable_shared_from_this const &) BOOST_SP_NOEXCEPT
  28. {
  29. }
  30. enable_shared_from_this & operator=(enable_shared_from_this const &) BOOST_SP_NOEXCEPT
  31. {
  32. return *this;
  33. }
  34. ~enable_shared_from_this() BOOST_SP_NOEXCEPT // ~weak_ptr<T> newer throws, so this call also must not throw
  35. {
  36. }
  37. public:
  38. shared_ptr<T> shared_from_this()
  39. {
  40. shared_ptr<T> p( weak_this_ );
  41. BOOST_ASSERT( p.get() == this );
  42. return p;
  43. }
  44. shared_ptr<T const> shared_from_this() const
  45. {
  46. shared_ptr<T const> p( weak_this_ );
  47. BOOST_ASSERT( p.get() == this );
  48. return p;
  49. }
  50. weak_ptr<T> weak_from_this() BOOST_SP_NOEXCEPT
  51. {
  52. return weak_this_;
  53. }
  54. weak_ptr<T const> weak_from_this() const BOOST_SP_NOEXCEPT
  55. {
  56. return weak_this_;
  57. }
  58. public: // actually private, but avoids compiler template friendship issues
  59. // Note: invoked automatically by shared_ptr; do not call
  60. template<class X, class Y> void _internal_accept_owner( shared_ptr<X> const * ppx, Y * py ) const BOOST_SP_NOEXCEPT
  61. {
  62. if( weak_this_.expired() )
  63. {
  64. weak_this_ = shared_ptr<T>( *ppx, py );
  65. }
  66. }
  67. private:
  68. mutable weak_ptr<T> weak_this_;
  69. };
  70. } // namespace boost
  71. #endif // #ifndef BOOST_SMART_PTR_ENABLE_SHARED_FROM_THIS_HPP_INCLUDED