EnableSharedFromThis.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #ifndef __DAHUA_MEMORY_ENABLESHAREDFROMTHIS_H__
  2. #define __DAHUA_MEMORY_ENABLESHAREDFROMTHIS_H__
  3. #include "Memory/SharedPtr.h"
  4. #include "Memory/WeakPtr.h"
  5. namespace Dahua {
  6. namespace Memory {
  7. template<class T> class TEnableSharedFromThis
  8. {
  9. protected:
  10. TEnableSharedFromThis()
  11. {
  12. }
  13. TEnableSharedFromThis(TEnableSharedFromThis const &)
  14. {
  15. }
  16. TEnableSharedFromThis & operator=(TEnableSharedFromThis const &)
  17. {
  18. return *this;
  19. }
  20. ~TEnableSharedFromThis()
  21. {
  22. }
  23. public:
  24. TSharedPtr<T> shared_from_this()
  25. {
  26. TSharedPtr<T> p( weak_this_ );
  27. assert( p.get() == this );
  28. return p;
  29. }
  30. TSharedPtr<T const> shared_from_this() const
  31. {
  32. TSharedPtr<T const> p( weak_this_ );
  33. assert( p.get() == this );
  34. return p;
  35. }
  36. public: // actually private, but avoids compiler template friendship issues
  37. template<class X, class Y> void _internal_accept_owner( TSharedPtr<X> const * ppx, Y * py ) const
  38. {
  39. if( weak_this_.expired() )
  40. {
  41. weak_this_ = TSharedPtr<T>( *ppx, py );
  42. }
  43. }
  44. private:
  45. mutable TWeakPtr<T> weak_this_;
  46. };
  47. } // namespace Memory
  48. }// namesapce Dahua
  49. #endif // end of __DAHUA_MEMORY_ENABLESHAREDFROMTHIS_H__