diff --git a/base/include/refbase.h b/base/include/refbase.h index 4c4c24b3cf2b6cac893b562ed349ac651fc880d2..10fdf2851659cdfd3e3bbae2666baf3395a29212 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 fd314d1e04b35740179288cbfc9d2c6ce6838868..8cc13144944d4c0db562900e2ed0516ec21f0031 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()