I am trying to save objects in a stl container (in this case a vector) and I want the container to destroy the objects when it is destroyed, but I can not fully figure out the details.
One of the ways that I don't want to do this is simply using it as
vector<MyClass> myVec; myVec.push_back(MyClass(...));
due to the fact that the constructor is called twice (once in the code above, then copy the constructor in the vector) and the destructor once.
The most direct alternative is to use pointers to store dynamically allocated objects, but then the MyClass destructor will not be called when the vector is destroyed. Saving auto_ptr instead of regular pointers gives an error with myVec.push_back (...) .
In any case, in order to avoid the first option, when the container destructor calls the element destructor?
Thank you for your responses!
EDIT
Consider a similar problem; how to implement a container that owns objects using an abstract base class. The unique pointer (Boost unique_ptr) does not have copy constructors, so do not use it directly.
class A {};
source share