"Johnny Hansen" <webmaster@suxx.dk> wrote in message
news:cjv9b9$f9e$1@news.cybercity.dk...[color=blue]
> 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?
> [...][/color]
Well, first consider using a reference-counted pointer library. If you want
to write your own, then take a look at the FAQ's answers about reference
counting (
http://www.parashift.com/c++-faq-lite/ Section 16 items 21 "How do
I do simple reference counting" on), because they contain useful snippets of
code for implementing reference counting.
Now, once you have a working reference-counted smart pointer stored in a
std::list or std::vector, removing elements so that the managed
reference-counted object may be deallocated is about as simple as removing
any other element from the container. A simple example (using std::list)
std::list<smartpointertype>::iterator it = /* something to remove */;
myList.erase( it );
will remove the smart pointer from the std::list, causing the smart
pointer's destructor to be invoked, which will cause the managed object's
reference count to be decreased by one (and deallocated, etc if
appropriate).
--
David Hilsee