Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
1.9 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // $NoKeywords: $
  4. //=============================================================================
  5. #ifndef GCREFCOUNT_H
  6. #define GCREFCOUNT_H
  7. #include "tier0/memdbgon.h"
  8. namespace GCSDK
  9. {
  10. // Base class for ref counted classes. Derive from this to be refcounted. Note:
  11. // you can no longer be deleted directly or declared on the stack. Make your
  12. // derived class' destructor private to ensure you can't be deleted directly or declared
  13. // on the stack.
  14. // utility class
  15. template< class T >
  16. class CAutoPtr
  17. {
  18. T *m_pT;
  19. public:
  20. CAutoPtr()
  21. {
  22. m_pT = NULL;
  23. }
  24. ~CAutoPtr()
  25. {
  26. delete m_pT;
  27. }
  28. T *reset( T *p )
  29. {
  30. delete m_pT;
  31. m_pT = p;
  32. return m_pT;
  33. }
  34. T *TakeOwnership()
  35. {
  36. T *p = m_pT;
  37. m_pT = NULL;
  38. return p;
  39. }
  40. T *release( )
  41. {
  42. T *pT = m_pT;
  43. m_pT = NULL;
  44. return pT;
  45. }
  46. T *operator->()
  47. {
  48. return m_pT;
  49. }
  50. operator T*()
  51. {
  52. return m_pT;
  53. }
  54. protected:
  55. T *operator=(T*p)
  56. {
  57. AssertMsg( NULL == m_pT, "If this assert fires, you're leaking.\n" );
  58. m_pT = p;
  59. return m_pT;
  60. }
  61. };
  62. class CRefCount
  63. {
  64. public:
  65. CRefCount() { m_cRef = 1; } // we are born with a ref count of 1
  66. // increment ref count
  67. int AddRef() { return ThreadInterlockedIncrement( &m_cRef ); }
  68. // delete ourselves when ref count reaches 0
  69. int Release()
  70. {
  71. Assert( m_cRef > 0 );
  72. int cRef = ThreadInterlockedDecrement( &m_cRef );
  73. if ( 0 == cRef )
  74. DestroyThis();
  75. return cRef;
  76. }
  77. protected:
  78. // Classes that derive from this should make their destructors private and virtual!
  79. virtual ~CRefCount() { Assert( 0 == m_cRef ); }
  80. virtual void DestroyThis() { delete this; } // derived classes may override this if they want to be part of a mem pool
  81. volatile int32 m_cRef; // ref count of this object
  82. };
  83. #define SAFE_RELEASE( x ) if ( NULL != ( x ) ) { ( x )->Release(); x = NULL; }
  84. } // namespace GCSDK
  85. #include "tier0/memdbgoff.h"
  86. #endif // GCREFCOUNT_H