現在、iveは以下を使用していくつかの参照カウントクラスを取得しています。
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呼び出しの数を最小限に抑えたパフォーマンスクリティカルなコードの1ビットまたは2ビットで)。
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);
}
ThreadA ThreadB t = CreateTexture( "ball.png"); t-> IncRef(); ... use t ... t2 = CreateTexture( "ball.png"); // return * 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++で高速参照カウントを行うためのクリーンな方法はありますか?