enable_shared_from_this.hpp 2.0 KB

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