Problem with Reference counter
Mar 17, 2011 at 11:27am UTC
Heya guys!
I'm currently implementing a template class that will handle reference counting for me and it works great except for this 1 problem. When i return my reference in my function. It decreases the ref-counter and then increases it. I hoped it would be done the other way around because now the ref counter reaches 0 when it decreases the refcounter and the object the ref counter holds is destroyed.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
class RefCounted
{
public :
RefCounted() : m_ReferenceCounter(0){}
virtual ~RefCounted(){}
void AddRef()
{
++m_ReferenceCounter;
}
mgUint32 GetRefCount()
{
return m_ReferenceCounter;
}
// Returns the ref counter
mgUint32 Release()
{
--m_ReferenceCounter;
if ( m_ReferenceCounter == 0 )
{
Destroy();
}
return m_ReferenceCounter;
}
virtual void Destroy() = 0;
private :
mgUint32 m_ReferenceCounter;
};
template <class T>
class ReferenceCounter
{
friend class ReferenceCounter;
public :
ReferenceCounter ()
{
m_pClass = NULL;
}
ReferenceCounter (T* pClass)
{
m_pClass = pClass;
m_pClass->AddRef();
}
ReferenceCounter& operator = (const ReferenceCounter& rhs)
{
Release();
m_pClass = rhs.m_pClass;
m_pClass->AddRef();
return *this ;
}
T* operator = (const T* pClass)
{
Release();
m_pClass = pClass;
m_pClass->AddRef();
return this ;
}
T* operator -> ()
{
return m_pClass;
}
~ReferenceCounter()
{
Release();
}
private :
void Release()
{
if ( m_pClass )
{
if ( m_pClass->Release() == 0 )
{
delete m_pClass;
}
m_pClass = NULL;
}
}
T* m_pClass;
};
typedef ReferenceCounter<CTexture> TextureRef;
My Texture class inherits from RefCounted.
In my TextureManager I do the following:
1 2 3 4
TextureRef Texture = new CTexture;
Texture->Create( Directory, FileName );
m_Textures.push_back(Texture);
return Texture; // <---- The problem
So it's in this last row my problem reveals itself. Any1 got any ideas what i could change to make this work?
Mar 17, 2011 at 11:32am UTC
When i return my reference in my function.
You must pass reference counted objects by value.
Mar 17, 2011 at 11:42am UTC
Yeah I just figured it out myself :D
The compiler was of course doing it's own copy of my reference and then returned that and i didn't have a constructor for that in ReferenceCounter.
So i added:
1 2 3 4 5
ReferenceCounter (const ReferenceCounter& rhs)
{
m_pClass = rhs.m_pClass;
m_pClass->AddRef();
}
Works wonders now, sorry for posting for nothing and thx kbw^^
Topic archived. No new replies allowed.