RefCounted.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #pragma once
  4. #ifdef URHO3D_IS_BUILDING
  5. #include "Urho3D.h"
  6. #else
  7. #include <Urho3D/Urho3D.h>
  8. #endif
  9. namespace Urho3D
  10. {
  11. /// Reference count structure.
  12. struct RefCount
  13. {
  14. /// Construct.
  15. RefCount() :
  16. refs_(0),
  17. weakRefs_(0)
  18. {
  19. }
  20. /// Destruct.
  21. ~RefCount()
  22. {
  23. // Set reference counts below zero to fire asserts if this object is still accessed
  24. refs_ = -1;
  25. weakRefs_ = -1;
  26. }
  27. /// Reference count. If below zero, the object has been destroyed.
  28. int refs_;
  29. /// Weak reference count.
  30. int weakRefs_;
  31. };
  32. /// Base class for intrusively reference-counted objects. These are noncopyable and non-assignable.
  33. class URHO3D_API RefCounted
  34. {
  35. public:
  36. /// Construct. Allocate the reference count structure and set an initial self weak reference.
  37. RefCounted();
  38. /// Destruct. Mark as expired and also delete the reference count structure if no outside weak references exist.
  39. virtual ~RefCounted();
  40. /// Prevent copy construction.
  41. RefCounted(const RefCounted& rhs) = delete;
  42. /// Prevent assignment.
  43. RefCounted& operator =(const RefCounted& rhs) = delete;
  44. /// Increment reference count. Can also be called outside of a SharedPtr for traditional reference counting.
  45. /// @manualbind
  46. void AddRef();
  47. /// Decrement reference count and delete self if no more references. Can also be called outside of a SharedPtr for traditional reference counting.
  48. /// @manualbind
  49. void ReleaseRef();
  50. /// Return reference count.
  51. /// @property
  52. int Refs() const;
  53. /// Return weak reference count.
  54. /// @property
  55. int WeakRefs() const;
  56. /// Return pointer to the reference count structure.
  57. RefCount* RefCountPtr() { return refCount_; }
  58. private:
  59. /// Pointer to the reference count structure.
  60. RefCount* refCount_;
  61. };
  62. }