enable_shared_from_this.hpp 2.2 KB

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