Hello,
I've been trying to implement smart pointers in C++ (combined with a
reference counter) because I want to do some memory management. My code
is based on the gamedev enginuity articles, various books and ...
whatever I could find on the subject :-)
I'll leave out the reference counter part because its pretty basic, but
my reference counter class is called xObject. My smart pointer class is
called xPointer.
My problem is that I can't figure out how to make my smart pointer
object a pointer. Look at the following code:
--------------- CUT
void test()
{
//xShaderResource is derived from xObject
class xPointer<xShaderResource> myShader2 = new xShaderResource();
myShader2->loadResource(NULL); //testing
}
--------------- CUT
This works like a charm. The xShaderResource object will be destroyed in
my garbage collector because myShader2 is beeing destructed after it
goes out of scope when test() returns.
So far so good, but what if let's say I have a vector/list with 1000+
xPointer objects (imagine a resource manager)? They will never go out of
scope, right?
What I need is to do something like this:
--------------- CUT
class xPointer<xShaderResource> *myShader2 = new
xPointer<xShaderResource>(new xShaderResource());
myShader2->loadResource(NULL);
--------------- CUT
This should enable me to run through the list and do something like this:
delete (*iterator);
on relevant objects thus forcing them to go away and get collcected. Can
this be done? I kinda figure I need to change/add my operators
somewhere, but I can't figure out how :-(
Can anyone help?
-------------------------------- Relevant code
template<class X>
class xPointer
{
protected:
X* obj;
public:
xPointer()
{
obj = 0;
}
xPointer(X *oP)
{
obj = 0;
*this = oP;
}
~xPointer()
{
if( obj )
obj->Release();
}
X& operator*(void) { return *obj; }
void operator =(X *oP)
{
if( obj )
obj->Release();
obj = oP;
if( obj )
obj->Alloc();
}
void operator =(const xPointer<X> &oP)
{
if( obj )
obj->Release();
obj = oP.obj;
if( obj )
obj->Alloc();
}
X* operator ->(void)
{
return obj;
}
};