this is a question about which class does a free on shared pointers.
So I have a class hierarchy, base and derivedA and derivedB and derivedC all from base. Base has some virtual functions.
I have a class, Holder, it has a collection that holds instances of derivedA, derivedB and derivedC. So an instance of Holder is created, instances of the derived classes are dynamically created and add their pointers to the containers. I add the pointers so I can iterate through the container and call base->virtualFunction. I new the objects because otherwise an instance created on the stack is destroyed when it goes out of scope.
class Base;
class DerivedA : public base;
class DerivedB : public base;
class DerivedC : public base;
class Holder {
std::vector<Base*> collection;
void add(Base* base);
}
Holder holder;
DerivedA* da = new DerivedA;
DerivedB* db = new DerivedB;
holder.add(da);
holder.add(db);
who is to call delete on da and db?
Any other way to design this for the deletion concern goes away?
Thanks
Reza
My question is first off, which class should be responsible to free the dynamically created the derived classes? The class the contains the list
The simpler way ? Change your vector to become aware of ownership.
is such a vector, especially suited for polymorphic data:
virtual Base* clone() const;)Base&instead of aBase*)In C++11, another alternative could be
std::vector< std::unique_ptr<Base> >.