RefCounted.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Container/RefCounted.h"
  5. #include "../DebugNew.h"
  6. namespace Urho3D
  7. {
  8. RefCounted::RefCounted() :
  9. refCount_(new RefCount())
  10. {
  11. // Hold a weak ref to self to avoid possible double delete of the refcount
  12. (refCount_->weakRefs_)++;
  13. }
  14. RefCounted::~RefCounted()
  15. {
  16. assert(refCount_);
  17. assert(refCount_->refs_ == 0);
  18. assert(refCount_->weakRefs_ > 0);
  19. // Mark object as expired, release the self weak ref and delete the refcount if no other weak refs exist
  20. refCount_->refs_ = -1;
  21. (refCount_->weakRefs_)--;
  22. if (!refCount_->weakRefs_)
  23. delete refCount_;
  24. refCount_ = nullptr;
  25. }
  26. void RefCounted::AddRef()
  27. {
  28. assert(refCount_->refs_ >= 0);
  29. (refCount_->refs_)++;
  30. }
  31. void RefCounted::ReleaseRef()
  32. {
  33. assert(refCount_->refs_ > 0);
  34. (refCount_->refs_)--;
  35. if (!refCount_->refs_)
  36. delete this;
  37. }
  38. int RefCounted::Refs() const
  39. {
  40. return refCount_->refs_;
  41. }
  42. int RefCounted::WeakRefs() const
  43. {
  44. // Subtract one to not return the internally held reference
  45. return refCount_->weakRefs_ - 1;
  46. }
  47. }