What's the best way to have a collection of class instances, all derived from the same base class?

I have a set of classes, all of which are based on a common base. I need a collection (possibly list

) that will contain instances of derived classes of various types. Class operations will call virtual methods on collection instances. Of course I can't use list<Base>

, because holding the base class by value will strip the derived classes.

The obvious solution is to use list<Base*>

and transfer it to a class using a copy constructor, destructor, etc. The base class will have a virtual function duplicate

that is overloaded in each derived class to return a pointer to a copy of that derived class. The destructor must go through the list and delete

each item.

If there is a Boost way to do this, that's fine. I am already using Boost. It seems to me that using Boost shared pointers would be the best way to go. There will be an overhead in managing the total number of links, but it should be cheaper than the allocation / copying required in the case of a pointer. However, this would mean that copies of the collection will result in the same instance, and changing one copy will change the other.

I don't know yet how this code will actually be used. So I'm not sure if the semantics of the shared copy would be an issue. I don't think copies will be distributed, they just need to be reasonably processed.

Is there another way?

+3


source to share


1 answer


Say hello to Boost.PointerContainer . By default, they offer deep semantics when copying containers (this is configurable, however). Note that you need to implement a free method new_clone

for your abstract base class in the appropriate namespace.

Also, as a side note, please use std::vector

as the first choice container.



One more note, don't wrap container<Base*>

, but rather wrap Base*

in, you guessed it, a smart pointer. C ++ 11 suggests unique_ptr

if you don't want cross-ownership. unique_ptr

lets you move it, you can't copy it.

+10


source







All Articles