Re: How to copy a vector if pointers to base class
In article
<846b145e-a23f-464e-aefb-49bdedbfc7cc@25g2000hsx.googlegroups.com>,
Alex Snast <asnast@gmail.com> wrote:
Kai-Uwe Bux ????
Alex Snast wrote:
?
???
I'm trying to implement a copy constructor for a vector of pointers to
a base class (which is abstract)
???
My question is how would i know what kind of new type should i
allocate since the base poiner can have multipull meanings.
???
i know i can use dynamic_cast however i really don't like this
solution and i was wondering is i can do something better
?
The standard trick is to provide a virtual clone() member in the base
class.
You can then copy the vector by using std::transform with a back_inserter
and a functor like this
?
Base* deep_copy ( Base * ptr ) {
return( ptr->clone() );
?????
?
or some of these unreadable pointer to member function binders.
?
You can also google the archives for copy_ptr or clone_ptr to find smart
pointers with deep copy semantics. Those are non-standard and might make
your code harder to maintain for others since they might not be familiar
with those libraries. On the plus side, you don't need to do anything to
copy a vector of those since the copy constructor of the smart pointer will
to the job.
?
?
Best
?
Kai-Uwe Bux
Thanks for the help. Worked just find even though i haven't used
std::transform but rather wrote my own method
Storerepository::Storerepository(const Storerepository& rhs) throw(OutOfMemory)
{
try {
for (const_repertory_iterator cit = rhs.repertory_.begin();
cit != rhs.repertory_.end(); ++cit) {
this->repertory_.push_back((*cit)->clone());
}
}
catch(std::bad_alloc){
throw OutOfMemory();
}
}
Just for the record, Kai-Uwe was recommending something like this:
transform(rhs.repertory_.begin(), rhs.repertory_.end(),
back_inserter(repertory_), &deep_copy);
Or:
transform(rhs.repertory_.begin(), rhs.repertory_.end(),
back_inserter(repertory_), mem_fun(&Base::clone));
You can wrap the above to convert a bad_alloc into an OutOfMemory, but I
don't see a reason to bother...