Base: improve class 'Handle' efficiency

By replacing dynamic allocated QAtomicInt with std::atomic and making
most code inlined.
This commit is contained in:
Zheng, Lei
2022-09-03 00:36:31 +05:00
committed by Uwe
parent a8606ce05c
commit dc48c5debd
2 changed files with 41 additions and 54 deletions
-42
View File
@@ -25,52 +25,10 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <cassert>
# include <iostream>
#endif
#include <QAtomicInt>
#include "Handle.h"
using namespace Base;
//**************************************************************************
// Construction/Destruction
Handled::Handled()
: _lRefCount(new QAtomicInt(0))
{
}
Handled::~Handled()
{
if (static_cast<int>(*_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<int>(*_lRefCount);
}
const Handled& Handled::operator = (const Handled&)
{
// we must not assign _lRefCount
return *this;
}
+41 -12
View File
@@ -29,8 +29,9 @@
#include <FCGlobal.h>
#endif
class QAtomicInt;
#include <assert.h>
#include <atomic>
#include <iostream>
namespace Base
{
@@ -72,6 +73,18 @@ public:
_toHandle->unref();
}
void reset(const Reference<T> &p=Reference<T>()) {
*this = p;
}
void swap(Reference<T> &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<int> _lRefCount;
};
} // namespace Base