Ive is currently getting some counted classes using the following:
class RefCounted { public: void IncRef() { ++refCnt; } void DecRef() { if(!--refCnt)delete this; } protected: RefCounted():refCnt(0){} private: unsigned refCnt;
I also have a class of smart pointers that handles reference counting, although it is not used uniformly (for example, in one or two bits of a critical performance code, where I minimized the number of calls to IncRef and 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; }
For general use of the classes themselves, I plan to use a read / write lock system, however I really do not need to create a write lock for every call to IncRef and DecRef.
I also just thought of a scenario in which a pointer might be invalid just before the IncRef call, think:
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
So, I think I need to completely change the reference counting model, the reason I added ref after returning to the design was to support things like the following:
MyObj->GetSomething()->GetSomethingElse()->DoSomething();
instead of:
SomeObject a = MyObj->GetSomething(); AnotherObject *b = a->GetSomethingElse(); b->DoSomething(); b->DecRef(); a->DecRef();
Is there a clean way to quickly count references in C ++ in a multi-threaded environment?
c ++ multithreading reference-counting
Fire lancer
source share