From 85fd9da92a07017762ce08d99b9f3b879d61dd70 Mon Sep 17 00:00:00 2001 From: Xi_Yuhao Date: Fri, 11 Mar 2022 17:37:42 +0800 Subject: [PATCH] refbase bugfix: Signed-off-by: Xi_Yuhao --- base/include/refbase.h | 2 ++ base/src/refbase.cpp | 48 +++++++++++++++++++----------------------- 2 files changed, 24 insertions(+), 26 deletions(-) diff --git a/base/include/refbase.h b/base/include/refbase.h index 4c4c24b..10fdf28 100755 --- a/base/include/refbase.h +++ b/base/include/refbase.h @@ -60,6 +60,8 @@ public: int DecWeakRefCount(const void *objectId); + int DecWeakAfterStrongChanged(const void *objectId, int strongRefCount); + int GetWeakRefCount(); void SetAttemptAcquire(); diff --git a/base/src/refbase.cpp b/base/src/refbase.cpp index fd314d1..8cc1314 100755 --- a/base/src/refbase.cpp +++ b/base/src/refbase.cpp @@ -148,24 +148,26 @@ int RefCounter::DecWeakRefCount(const void*) curCount = atomicWeak_.fetch_sub(1, std::memory_order_release); } - if (curCount != 1) { - return curCount; + if (curCount == 1) { + if (callback_) { + callback_(); + } + } + + return curCount; +} + +int RefCounter::DecWeakAfterStrongChanged(const void* objectId, int strongRefCount) +{ + int curCount = GetWeakRefCount(); + if (curCount > 0 && (strongRefCount != 0 || IsLifeTimeExtended())) { + curCount = atomicWeak_.fetch_sub(1, std::memory_order_release); } - if (IsLifeTimeExtended() && GetStrongRefCount() == 0) { + if ((curCount == 1 && IsLifeTimeExtended()) || (strongRefCount == 0 && !IsLifeTimeExtended())) { if (callback_) { callback_(); } - } else { - // only weak ptr case: no strong reference, delete the object - if (GetStrongRefCount() == INITIAL_PRIMARY_VALUE) { - if (callback_) { - callback_(); - } - } else { - // free RefCounter - DecRefCount(); - } } return curCount; @@ -313,10 +315,7 @@ RefBase::~RefBase() { if (refs_ != nullptr) { refs_->RemoveCallback(); - if ((refs_->IsLifeTimeExtended() && refs_->GetWeakRefCount() == 0) - || refs_->GetStrongRefCount() == INITIAL_PRIMARY_VALUE) { - refs_->DecRefCount(); - } + refs_->DecRefCount(); refs_ = nullptr; } } @@ -339,8 +338,7 @@ void RefBase::IncStrongRef(const void *objectId) } if (refs_->IsAttemptAcquireSet()) { refs_->ClearAttemptAcquire(); - refs_->DecStrongRefCount(objectId); - refs_->DecWeakRefCount(objectId); + DecStrongRef(objectId); } } @@ -354,14 +352,12 @@ void RefBase::DecStrongRef(const void *objectId) const int curCount = refs->DecStrongRefCount(objectId); if (curCount == 1) { OnLastStrongRef(objectId); - if (!refs->IsLifeTimeExtended()) { - if (refs->callback_) { - refs->callback_(); - } - } } - - refs->DecWeakRefCount(objectId); + if (curCount != INITIAL_PRIMARY_VALUE && curCount > 0) { + refs->DecWeakAfterStrongChanged(objectId, curCount - 1); + } else { + refs->DecWeakRefCount(objectId); + } } int RefBase::GetSptrRefCount() -- Gitee