I'm trying to save objects in an stl container (in this case a vector) and want the container to destroy the objects at its destruction, but I can't quite figure out the details.
One way I don't want to do it is simply using it like
vector<MyClass> myVec;
myVec.push_back(MyClass(...));
due to the fact that the constructor here is called twice (once in above code, then copy constructor in vector) and the destructor once.
The most direct alternative is to use pointers to store dynamically allocated objects, but then the destructor of MyClass won't be called at vector destruction. Storing auto_ptr instead of normal pointers gives an error at myVec.push_back(...).
Is there anyway to avoid the first option while having the container's destructor call the elements' destructor?
Thank you for your answers!
EDIT
Consider the similar problem; how to implement a container owning objects using an abstract base class. Unique pointer (Boost's unique_ptr) don't have copy constructors so one can't use that directly.
class A {}; // Abstract base class.
class B : public A {}; // Sub class.
...
vector<A *> vec;
vec.push_back(new B());
// At destruction of vec, destroy elements left in container.