目前,我使用以下方法获得了一些引用计数类:
class RefCounted
{
public:
void IncRef()
{
++refCnt;
}
void DecRef()
{
if(!--refCnt)delete this;
}
protected:
RefCounted():refCnt(0){}
private:
unsigned refCnt;
//not implemented
RefCounted(RefCounted&);
RefCounted& operator = (RefCounted&};
};
我还有一个处理引用计数的智能指针类,尽管它没有统一使用(例如,在一个或两个性能关键代码中,我最小化了 IncRef 和 DecRef 调用的数量)。
template<class T>class RefCountedPtr
{
public:
RefCountedPtr(T *p)
:p(p)
{
if(p)p->IncRef();
}
~RefCountedPtr()
{
if(p)p->DecRef();
}
RefCountedPtr<T>& operator = (T *newP)
{
if(newP)newP->IncRef();
if(p) p ->DecRef();
p = newP;
return *this;
}
RefCountedPtr<T>& operator = (RefCountedPtr<T> &newP)
{
if(newP.p)newP.p->IncRef();
if(p) p ->DecRef();
p = newP.p;
return *this;
}
T& operator *()
{
return *p;
}
T* operator ->()
{
return p;
}
//comparison operators etc and some const versions of the above...
private:
T *p;
};
对于类本身的一般用途,我计划使用读取器/写入器锁定系统,但是我真的不想为每个单独的 IncRef 和 DecRef 调用获取写入器锁。
我还只是想到了在 IncRef 调用之前指针可能无效的情况,请考虑:
class Texture : public RefCounted
{
public:
//...various operations...
private:
Texture(const std::string &file)
{
//...load texture from file...
TexPool.insert(this);
}
virtual ~Texture()
{
TexPool.erase(this);
}
freind CreateTextureFromFile;
};
Texture *CreateTexture(const std::string &file)
{
TexPoolIterator i = TexPool.find(file);
if(i != TexPool.end())return *i;
else return new Texture(file);
}
线程A 线程B t = CreateTexture("ball.png"); t->IncRef(); ...使用 t... t2 = CreateTexture("ball.png");//返回 *t ...线程暂停... t->DecRef();//删除t ... ... t2->IncRef();//错误
所以我想我需要完全改变引用计数模型,我在设计中返回后添加引用的原因是为了支持以下内容:
MyObj->GetSomething()->GetSomethingElse()->DoSomething();
而不必:
SomeObject a = MyObj->GetSomething();
AnotherObject *b = a->GetSomethingElse();
b->DoSomething();
b->DecRef();
a->DecRef();
在多线程环境中,C++ 中是否有一种快速引用计数的干净方法?