From dc48c5debd8f2e77aa52e39576d957cd33fb888e Mon Sep 17 00:00:00 2001 From: "Zheng, Lei" Date: Thu, 15 Apr 2021 08:53:44 +0800 Subject: [PATCH] Base: improve class 'Handle' efficiency By replacing dynamic allocated QAtomicInt with std::atomic and making most code inlined. --- src/Base/Handle.cpp | 42 ----------------------------------- src/Base/Handle.h | 53 +++++++++++++++++++++++++++++++++++---------- 2 files changed, 41 insertions(+), 54 deletions(-) diff --git a/src/Base/Handle.cpp b/src/Base/Handle.cpp index c02189b83f..5202530ffd 100644 --- a/src/Base/Handle.cpp +++ b/src/Base/Handle.cpp @@ -25,52 +25,10 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include #endif -#include - #include "Handle.h" using namespace Base; -//************************************************************************** -// Construction/Destruction - -Handled::Handled() - : _lRefCount(new QAtomicInt(0)) -{ -} - -Handled::~Handled() -{ - if (static_cast(*_lRefCount) != 0) - std::cerr << "Reference counter of deleted object is not zero!!!!!" << std::endl; - delete _lRefCount; -} - -void Handled::ref() const -{ - _lRefCount->ref(); -} - -void Handled::unref() const -{ - assert(*_lRefCount > 0); - if (!_lRefCount->deref()) { - delete this; - } -} - -int Handled::getRefCount() const -{ - return static_cast(*_lRefCount); -} - -const Handled& Handled::operator = (const Handled&) -{ - // we must not assign _lRefCount - return *this; -} diff --git a/src/Base/Handle.h b/src/Base/Handle.h index c3e05ffb80..2e2ad6fe8a 100644 --- a/src/Base/Handle.h +++ b/src/Base/Handle.h @@ -29,8 +29,9 @@ #include #endif - -class QAtomicInt; +#include +#include +#include namespace Base { @@ -72,6 +73,18 @@ public: _toHandle->unref(); } + void reset(const Reference &p=Reference()) { + *this = p; + } + + void swap(Reference &p) { + if(*this != p) { + auto tmp = p; + p = *this; + *this = tmp; + } + } + //************************************************************************** // operator implementation @@ -160,20 +173,36 @@ private: class BaseExport Handled { public: - Handled(); - virtual ~Handled(); + Handled() + :_lRefCount(0) + {} - void ref() const; - void unref() const; + Handled(const Handled&) = delete; - int getRefCount() const; - const Handled& operator = (const Handled&); + virtual ~Handled() + { + if (_lRefCount != 0) + std::cerr << "Reference counter of deleted object is not zero!!!!!" << std::endl; + } + + void ref() const {++_lRefCount;} + + int unref() const + { + int res = --_lRefCount; + if (res == 0) + delete this; + else + assert(res>0); + return res; + } + + int getRefCount(void) const {return _lRefCount;} + + const Handled& operator = (const Handled&) {return *this;} private: - Handled(const Handled&); - -private: - QAtomicInt* _lRefCount; + mutable std::atomic _lRefCount; }; } // namespace Base