Smart Pointers and Polymorphic Collections

Started by
2 comments, last by alvaro 15 years, 7 months ago
Ok so this is a problem i stumbled upon the other day. I have a couple of ideas that i will keep to myself for the early part of this topic, so i don't taint the replies. I have a codebase in which everything reference counted, so:
class CB : public class CA
{
};
Then we have declarations like the following:
RefCtd< CA > A;
RefCtd< CB > B;
What is required of class RefCtd for me to be able to store a collection of A's:
std::vector< A > myCollection;
and be able to store smart-pointed entities of derrived classes to it, like so:
myCollection.push_back( InstanceOfB );
Is this accomplishable? If so, what would you do/ have you done? Thanks,
Advertisement
if CB inherits from CA, wouldn't it be possible for you to store both CA* and CB* in a smart pointer of type RefCtd< CA >, which in turn you can store in std::vector< RefCtd< CA > > ?
Might be wrong though, or I just missed the point entirely :)
It is possible. I would do it by using a pre-existing and tested, reference-counting smart pointer implementation that is known to support this use case: boost::shared_ptr. I would then just create a std::vector<boost::shared_ptr<Base> >, and happily .push_back(boost::shared_ptr<Base>(new Derived())) as desired.
What Zahlman said. Another alternative (possibly better) is to use the Boost Pointer Container Library.

This topic is closed to new replies.

Advertisement