WeakPtr.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #ifndef __DAHUA_MEMORY_WEAK_PTR_H__
  2. #define __DAHUA_MEMORY_WEAK_PTR_H__
  3. #include "Memory/SharedPtr.h"
  4. namespace Dahua {
  5. namespace Memory {
  6. template < class T >
  7. class TWeakPtr
  8. {
  9. typedef TWeakPtr<T> this_type;
  10. typedef T element_type;
  11. #ifdef DAHUA_NO_MEMBER_TEMPLATE_FRIENDS
  12. public:
  13. #else
  14. template<class Y> friend class TWeakPtr;
  15. template<class Y> friend class TSharedPtr;
  16. #endif
  17. T* m_ptr;
  18. Detail::weak_count m_pn;
  19. public:
  20. TWeakPtr()
  21. : m_ptr(NULL), m_pn()
  22. {
  23. }
  24. TWeakPtr( TSharedPtr< T > const& rhs )
  25. : m_ptr( rhs.px)
  26. , m_pn( rhs.pn)
  27. {
  28. }
  29. TWeakPtr& operator=( TWeakPtr< T > const& other )
  30. {
  31. m_ptr = other.m_ptr;
  32. m_pn = other.m_pn;
  33. return *this;
  34. }
  35. template<class Y>
  36. TWeakPtr(TWeakPtr<Y> const & other, Detail::dynamic_cast_tag)
  37. : m_ptr( dynamic_cast<element_type *>(other.m_ptr) )
  38. , m_pn( other.m_pn )
  39. {
  40. if( m_ptr == 0 ) // need to allocate new counter -- the cast failed
  41. {
  42. m_pn = Detail::weak_count();
  43. }
  44. }
  45. template<class Y>
  46. TWeakPtr(TWeakPtr<Y> const & other, Detail::static_cast_tag)
  47. : m_ptr( static_cast<element_type *>(other.m_ptr) )
  48. , m_pn( other.m_pn )
  49. {
  50. }
  51. bool expired()
  52. {
  53. return m_pn.use_count() == 0;
  54. }
  55. TSharedPtr<T> lock() const
  56. {
  57. return TSharedPtr<T>( *this, Detail::sp_nothrow_tag() );
  58. }
  59. void reset()
  60. {
  61. this_type().swap((*this) );
  62. }
  63. void swap( TWeakPtr<T>& other )
  64. {
  65. std::swap( m_ptr, other.m_ptr );
  66. m_pn.swap( other.m_pn );
  67. }
  68. };
  69. } // namespace Memory
  70. } // namespace Dahua
  71. #endif // end of __DAHUA_MEMORY_WEAK_PTR_H__