I can clearly see the benefits of using smartpointers in complex software like game engines. However there is one thing that really makes me confused.
The whole idea of smart pointers is the reference counter. I have a ObjectFactory which constructs and encapsulates a user-provided class in a GameObject template. The template also gets assigned an Id of the object, it uses custom allocation/deallocation, etc
template <class T>
class Object
{
public:
inline Object(IMemoryManager* memMgr)
{
Init();
if (memMgr)
{
mMemoryMgr = memMgr; mObj = (T*) mMemoryMgr->Allocate(sizeof(T));
mRefCount = 1;
}
}
inline Object(bool UseMemPool, IMemoryManager* memMgr)
{
Init(); if (memMgr)
{
mMemoryMgr = memMgr;
mObj = (T*) mMemoryMgr->Allocate(sizeof(T),UseMemPool);
mRefCount = 1;
mUseMemoryPool = UseMemPool;
}
} inline Object(Object<T>& ptr)
{
Init();
mObj = ptr.mObj;
mRefCount = ptr.mRefCount;
mUseMemoryPool = ptr.mUseMemoryPool;
mMemoryMgr = ptr.mMemoryMgr;
IncRef();
}
inline ~Object()
{
if (mObj && mMemoryMgr)
{
DecRef();
if (mRefCount <= 0)
{
mMemoryMgr->Deallocate(mObj,mUseMemoryPool);
}
mObj = NULL;
}
}
//......
The ObjectFactory keeps its constructed gameobjects in a map, because at engine tick() it proceeds to call Draw() / Update() on each gameobject. Which means there should always be a reference to that object in the objectfactorys map, right?
And thats what I dont understand, or I probably designed it wrong. Since there is always a reference back in the ObjectFactory (an engine-component that dosn't get destroyed untill the engine stops) no memory will ever be freed untill the engine stops.
And even if memory would get freed outside of the ObjectFactory, there would be a dangling pointer in the ObjectFactory?
That's what makes simple handles seem ideal to me, although of course they don't auto-delete themselves.
Can anyone explain how this is supposed to work?
Thanks