In a related question I asked about creating a generic container. Using polymorphic templates seems like the right way to go.
However, I can’t for the life of me figure out how a destructor should be written. I want the owner of the memory allocated to be the containers even if the example constructor takes in an array of T (along with its dimensions), allocated at some other point.
I would like to be able to do something like
MyContainer<float> blah(); ... delete blah;
and
MyContainer<ComplexObjectType*> complexBlah(); ... delete complexBlah;`
Can I do something like this? Can I do it without smart pointers?
Again, thanks for your input.
I’d recommend if you want to store pointers to complex types, that you use your container as:
MyContainer<shared_ptr<SomeComplexType> >, and for primitive types just useMyContainer<float>.The
shared_ptrshould take care of deleting the complex type appropriately when it is destructed. And nothing fancy will happen when the primitive type is destructed.You don’t need much of a destructor if you use your container this way. How do you hold your items in the container? Do you use an STL container, or an array on the heap? An STL container would take care of deleting itself. If you delete the array, this would cause the destructor for each element to be executed, and if each element is a
shared_ptr, theshared_ptrdestructor will delete the pointer it itself is holding.