Reference.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Core/Atomics.h>
  6. JPH_NAMESPACE_BEGIN
  7. // Forward declares
  8. template <class T> class Ref;
  9. template <class T> class RefConst;
  10. /// Simple class to facilitate reference counting / releasing
  11. /// Derive your class from RefTarget and you can reference it by using Ref<classname> or RefConst<classname>
  12. ///
  13. /// Reference counting classes keep an integer which indicates how many references
  14. /// to the object are active. Reference counting objects are derived from RefTarget
  15. /// and staT & their life with a reference count of zero. They can then be assigned
  16. /// to equivalents of pointers (Ref) which will increase the reference count immediately.
  17. /// If the destructor of Ref is called or another object is assigned to the reference
  18. /// counting pointer it will decrease the reference count of the object again. If this
  19. /// reference count becomes zero, the object is destroyed.
  20. ///
  21. /// This provides a very powerful mechanism to prevent memory leaks, but also gives
  22. /// some responsibility to the programmer. The most notable point is that you cannot
  23. /// have one object reference another and have the other reference the first one
  24. /// back, because this way the reference count of both objects will never become
  25. /// lower than 1, resulting in a memory leak. By carefully designing your classes
  26. /// (and particularly identifying who owns who in the class hierarchy) you can avoid
  27. /// these problems.
  28. template <class T>
  29. class RefTarget
  30. {
  31. public:
  32. /// Constructor
  33. inline RefTarget() = default;
  34. inline RefTarget(const RefTarget &) { /* Do not copy refcount */ }
  35. inline ~RefTarget() { JPH_IF_ENABLE_ASSERTS(uint32 value = mRefCount.load(memory_order_relaxed);) JPH_ASSERT(value == 0 || value == cEmbedded); } ///< assert no one is referencing us
  36. /// Mark this class as embedded, this means the type can be used in a compound or constructed on the stack.
  37. /// The Release function will never destruct the object, it is assumed the destructor will be called by whoever allocated
  38. /// the object and at that point in time it is checked that no references are left to the structure.
  39. inline void SetEmbedded() const { JPH_IF_ENABLE_ASSERTS(uint32 old = ) mRefCount.fetch_add(cEmbedded, memory_order_relaxed); JPH_ASSERT(old < cEmbedded); }
  40. /// Assignment operator
  41. inline RefTarget & operator = (const RefTarget &) { /* Don't copy refcount */ return *this; }
  42. /// Get current refcount of this object
  43. uint32 GetRefCount() const { return mRefCount.load(memory_order_relaxed); }
  44. /// Add or release a reference to this object
  45. inline void AddRef() const
  46. {
  47. // Adding a reference can use relaxed memory ordering
  48. mRefCount.fetch_add(1, memory_order_relaxed);
  49. }
  50. inline void Release() const
  51. {
  52. #ifndef JPH_TSAN_ENABLED
  53. // Releasing a reference must use release semantics...
  54. if (mRefCount.fetch_sub(1, memory_order_release) == 1)
  55. {
  56. // ... so that we can use acquire to ensure that we see any updates from other threads that released a ref before deleting the object
  57. atomic_thread_fence(memory_order_acquire);
  58. delete static_cast<const T *>(this);
  59. }
  60. #else
  61. // But under TSAN, we cannot use atomic_thread_fence, so we use an acq_rel operation unconditionally instead
  62. if (mRefCount.fetch_sub(1, memory_order_acq_rel) == 1)
  63. delete static_cast<const T *>(this);
  64. #endif
  65. }
  66. /// INTERNAL HELPER FUNCTION USED BY SERIALIZATION
  67. static int sInternalGetRefCountOffset() { return offsetof(T, mRefCount); }
  68. protected:
  69. static constexpr uint32 cEmbedded = 0x0ebedded; ///< A large value that gets added to the refcount to mark the object as embedded
  70. mutable atomic<uint32> mRefCount = 0; ///< Current reference count
  71. };
  72. /// Pure virtual version of RefTarget
  73. class JPH_EXPORT RefTargetVirtual
  74. {
  75. public:
  76. /// Virtual destructor
  77. virtual ~RefTargetVirtual() = default;
  78. /// Virtual add reference
  79. virtual void AddRef() = 0;
  80. /// Virtual release reference
  81. virtual void Release() = 0;
  82. };
  83. /// Class for automatic referencing, this is the equivalent of a pointer to type T
  84. /// if you assign a value to this class it will increment the reference count by one
  85. /// of this object, and if you assign something else it will decrease the reference
  86. /// count of the first object again. If it reaches a reference count of zero it will
  87. /// be deleted
  88. template <class T>
  89. class Ref
  90. {
  91. public:
  92. /// Constructor
  93. inline Ref() : mPtr(nullptr) { }
  94. inline Ref(T *inRHS) : mPtr(inRHS) { AddRef(); }
  95. inline Ref(const Ref<T> &inRHS) : mPtr(inRHS.mPtr) { AddRef(); }
  96. inline Ref(Ref<T> &&inRHS) noexcept : mPtr(inRHS.mPtr) { inRHS.mPtr = nullptr; }
  97. inline ~Ref() { Release(); }
  98. /// Assignment operators
  99. inline Ref<T> & operator = (T *inRHS) { if (mPtr != inRHS) { Release(); mPtr = inRHS; AddRef(); } return *this; }
  100. inline Ref<T> & operator = (const Ref<T> &inRHS) { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; AddRef(); } return *this; }
  101. inline Ref<T> & operator = (Ref<T> &&inRHS) noexcept { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; inRHS.mPtr = nullptr; } return *this; }
  102. /// Casting operators
  103. inline operator T *() const { return mPtr; }
  104. /// Access like a normal pointer
  105. inline T * operator -> () const { return mPtr; }
  106. inline T & operator * () const { return *mPtr; }
  107. /// Comparison
  108. inline bool operator == (const T * inRHS) const { return mPtr == inRHS; }
  109. inline bool operator == (const Ref<T> &inRHS) const { return mPtr == inRHS.mPtr; }
  110. inline bool operator != (const T * inRHS) const { return mPtr != inRHS; }
  111. inline bool operator != (const Ref<T> &inRHS) const { return mPtr != inRHS.mPtr; }
  112. /// Get pointer
  113. inline T * GetPtr() const { return mPtr; }
  114. /// INTERNAL HELPER FUNCTION USED BY SERIALIZATION
  115. void ** InternalGetPointer() { return reinterpret_cast<void **>(&mPtr); }
  116. private:
  117. template <class T2> friend class RefConst;
  118. /// Use "variable = nullptr;" to release an object, do not call these functions
  119. inline void AddRef() { if (mPtr != nullptr) mPtr->AddRef(); }
  120. inline void Release() { if (mPtr != nullptr) mPtr->Release(); }
  121. T * mPtr; ///< Pointer to object that we are reference counting
  122. };
  123. /// Class for automatic referencing, this is the equivalent of a CONST pointer to type T
  124. /// if you assign a value to this class it will increment the reference count by one
  125. /// of this object, and if you assign something else it will decrease the reference
  126. /// count of the first object again. If it reaches a reference count of zero it will
  127. /// be deleted
  128. template <class T>
  129. class RefConst
  130. {
  131. public:
  132. /// Constructor
  133. inline RefConst() : mPtr(nullptr) { }
  134. inline RefConst(const T * inRHS) : mPtr(inRHS) { AddRef(); }
  135. inline RefConst(const RefConst<T> &inRHS) : mPtr(inRHS.mPtr) { AddRef(); }
  136. inline RefConst(RefConst<T> &&inRHS) noexcept : mPtr(inRHS.mPtr) { inRHS.mPtr = nullptr; }
  137. inline RefConst(const Ref<T> &inRHS) : mPtr(inRHS.mPtr) { AddRef(); }
  138. inline RefConst(Ref<T> &&inRHS) noexcept : mPtr(inRHS.mPtr) { inRHS.mPtr = nullptr; }
  139. inline ~RefConst() { Release(); }
  140. /// Assignment operators
  141. inline RefConst<T> & operator = (const T * inRHS) { if (mPtr != inRHS) { Release(); mPtr = inRHS; AddRef(); } return *this; }
  142. inline RefConst<T> & operator = (const RefConst<T> &inRHS) { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; AddRef(); } return *this; }
  143. inline RefConst<T> & operator = (RefConst<T> &&inRHS) noexcept { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; inRHS.mPtr = nullptr; } return *this; }
  144. inline RefConst<T> & operator = (const Ref<T> &inRHS) { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; AddRef(); } return *this; }
  145. inline RefConst<T> & operator = (Ref<T> &&inRHS) noexcept { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; inRHS.mPtr = nullptr; } return *this; }
  146. /// Casting operators
  147. inline operator const T * () const { return mPtr; }
  148. /// Access like a normal pointer
  149. inline const T * operator -> () const { return mPtr; }
  150. inline const T & operator * () const { return *mPtr; }
  151. /// Comparison
  152. inline bool operator == (const T * inRHS) const { return mPtr == inRHS; }
  153. inline bool operator == (const RefConst<T> &inRHS) const { return mPtr == inRHS.mPtr; }
  154. inline bool operator == (const Ref<T> &inRHS) const { return mPtr == inRHS.mPtr; }
  155. inline bool operator != (const T * inRHS) const { return mPtr != inRHS; }
  156. inline bool operator != (const RefConst<T> &inRHS) const { return mPtr != inRHS.mPtr; }
  157. inline bool operator != (const Ref<T> &inRHS) const { return mPtr != inRHS.mPtr; }
  158. /// Get pointer
  159. inline const T * GetPtr() const { return mPtr; }
  160. /// INTERNAL HELPER FUNCTION USED BY SERIALIZATION
  161. void ** InternalGetPointer() { return const_cast<void **>(reinterpret_cast<const void **>(&mPtr)); }
  162. private:
  163. /// Use "variable = nullptr;" to release an object, do not call these functions
  164. inline void AddRef() { if (mPtr != nullptr) mPtr->AddRef(); }
  165. inline void Release() { if (mPtr != nullptr) mPtr->Release(); }
  166. const T * mPtr; ///< Pointer to object that we are reference counting
  167. };
  168. JPH_NAMESPACE_END
  169. JPH_SUPPRESS_WARNING_PUSH
  170. JPH_CLANG_SUPPRESS_WARNING("-Wc++98-compat")
  171. namespace std
  172. {
  173. /// Declare std::hash for Ref
  174. template <class T>
  175. struct hash<JPH::Ref<T>>
  176. {
  177. size_t operator () (const JPH::Ref<T> &inRHS) const
  178. {
  179. return hash<T *> { }(inRHS.GetPtr());
  180. }
  181. };
  182. /// Declare std::hash for RefConst
  183. template <class T>
  184. struct hash<JPH::RefConst<T>>
  185. {
  186. size_t operator () (const JPH::RefConst<T> &inRHS) const
  187. {
  188. return hash<const T *> { }(inRHS.GetPtr());
  189. }
  190. };
  191. }
  192. JPH_SUPPRESS_WARNING_POP