I’m sitting here with the following class:
class TagCompound : public Tag
{
public:
// [...] Constructor and other methods
void insert(Tag *t);
// [...] more modifying methods
protected:
std::vector<Tag *> _values;
};
TagCompound::insert(Tag *t)
{
_values.push_back(t);
}
This is all fun and dandy and works with both stack and heap allocated objects of a class derived of Tag.
Of course, if the pointer supplied to TagCompound::insert() is allocated on the heap, it has to be deallocated somewhere outside. This means that every method that removes something from the vector has to return the removed pointer so the outside can free it again, if it has to.
I don’t like this, it’s messy and error prone if the caller forgets to delete it.
The other thing I tried out was simply assuming every pointer in the vector _values would be heap allocated and do the deletion in every function that somehow removed something from _values and have delete run on every remaining element in TagCompound::~TagCompound.
That of course completely ruled out stack pointers by causing an invalid deletion.
I also tried using std::auto_ptr but soon I found out that it doesn’t work with STL containers. There’s probably something from boost, but I don’t want to use boost (or any kind of third party library).
Was I already on the right way with one of these methods, or is there some kind of black magic that works even better?
You can use tr1::shared_ptr (or std::shared_ptr if you have a 0x compiler) with custom deleters for statically allocated objects (no-op deleters in this case).