Original Post
I want to use STL containers to hold pointers. The catch is, these pointers need to be deleted once the container item is disposed of. For example, if I have a vector called v, i should be able to call:
v.push_back( new SomeClass(...) );
and be able to rely on the fact that the memory get deallocated.
I figured one potential way would be to use "safe pointers" which encapsulate the pointer into a templatized class. Is "safe pointers" the right lingo? because I tried searching the forums for it, but didn't find anything useful. That being said, is there a "standard" class out there that I can use for that effect, or must I write my own?
I tried writing my own class, but I ran into some ... complications. Here is how i create a vector of pointers to some class X, and add a pointer to the list:
vector< SafePointer< X > > v;
v.push_back( new X(2) );
The problem with this, is that in order to push_back() an item, a temporary SafePointer is created. The temporary SafePointer is then copied using the copy constructor, and then destroyed. This is problematic indeed, because as soon as that temporary SafePointer variable goes out of scope, it deletes the memory that I just created, thereby making the element in vector invalid. Even more frustrating, is that fact that temporary variables are "const". As such, I can't tweak the copy constructor to flag a conditional delete boolean, so the old SafePointer knows not to delete itself.
So, what I am doing right now in my SafePointer class is to allocate the memory AGAIN during the copy constructor. While this works for simple cases, it isnt suitable for my application. I don't want to have to construct the pointer memory over again.
So, in short, how do i get this code to work right:
v.push_back( new SomeClass(...) );
?
Here is my condensed code for SafePointer:
[edited by - FrigidHelix on June 5, 2002 4:05:13 AM]
template <typename T>
class SafePointer
{
T* p;
public:
SafePointer(T* inP) : p(inP) { }
SafePointer( const SafePointer<T>& sp){ p = new T(*sp.p); }
~SafePointer() { if(p) delete p; }
T* operator->() { return p; }
};