Attualmente Ive ha ottenuto alcune classi di riferimento contato con la seguente:C++: Multi threading e riferimento contando
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&};
};
Ho anche una classe di puntatore intelligente che gestisce il conteggio di riferimento, tutti però la sua non è utilizzato in modo uniforme (ad esempio in uno o due bit di codice critico delle prestazioni, in cui ho ridotto al minimo il numero di chiamate IncRef e 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;
};
Per l'uso generale delle classi stesse che prevede di utilizzare un sistema di lettura/scrittura di blocco, ma realmente non vogliono avere a ottenere un blocco scrittore per ogni singola chiamata IncRef e DecRef.
ho anche pensato di uno scenario in cui il puntatore può essere invalidata solo prima della chiamata IncRef, considerare:
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");//returns *t ... thread suspended... t->DecRef();//deletes t ... ... t2->IncRef();//ERROR
quindi credo che ho bisogno di cambiare il modello di conteggio ref del tutto, la ragione ho aggiunto un ref dopo il ritorno nella progettazione è stato quello di sostenere le cose come la seguente:
MyObj->GetSomething()->GetSomethingElse()->DoSomething();
piuttosto che dover:
SomeObject a = MyObj->GetSomething();
AnotherObject *b = a->GetSomethingElse();
b->DoSomething();
b->DecRef();
a->DecRef();
Esiste un modo pulito per il conteggio dei riferimenti rapidi in C++ in un ambiente con più thread?
Usate 'boost :: shared_ptr': http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/shared_ptr. htm – avakar
Che è disponibile come std :: tr1 :: shared_ptr anche in alcuni compilatori – bdonlan