Reputation: 3740
I have a std::vector<std::unique_ptr<BaseType>>
. Is there any clean way to do a deep copy of the vector
?
The only thing that I can think of is to have a function that uses dynamic_cast
to retrieve the derived type, and then copy that into a new object held by a unique_ptr
. Given that I have control of all possible derived classes, this would be feasible. This has all kinds of obvious shortcomings.
Previously I had used a single class that was a union of all derived types. In attempting to get away from this I have encountered the situation of needing to copy the vector
.
Is there any good solution to this problem? The only solutions that I can come up with are hideously ugly and cause me great shame to even consider. This is one largish step in attempting to refactor/cleanup code that I work with.
The vector
is a member of a class that must be copyable. So, in this case, I just need to ensure that I can write a copy constructor for the containing class.
Upvotes: 1
Views: 770
Reputation: 5739
The easiest way is to implement some form of cloning, then using std::transform
:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <memory>
#include <vector>
struct base {
// For constructors and destructors, it's business as usual.
// Remember to implement the rule of five.
base() {std::cout << "new base\n";}
base(const base& o) {
std::cout << "copied base\n";
}
virtual ~base() {std::cout << "destructed base\n";}
// This is the virtual copy function. We need this because only
// the actual derived class will know how to copy itself. The
// only way to forward this knowledge to a pointer to the base
// class is via a virtual function.
// You can make this pure virtual, if you don't mind
// the base being abstract (or if you *want* to make it
// abstract). It'll be safer this way.
virtual base* copy() {return new base(*this);}
};
struct derived : base {
derived() : base() {std::cout << "new derived";}
derived(const derived& o) : base(o) {
std::cout << "copied derived\n";
}
virtual ~derived() {std::cout << "destructed derived\n";}
base* copy() override {return new derived(*this);}
};
// example of deep copying
int main() {
std::vector<std::unique_ptr<base>> v;
v.emplace_back(new base());
v.emplace_back(new derived());
std::vector<std::unique_ptr<base>> copy_of_v;
// The transformation merely calls copy(). Each object will be copied into
// an instance of the correct type.
std::transform(v.begin(), v.end(), std::back_inserter(copy_of_v), [](auto& item){
return std::unique_ptr<base>(item->copy());
});
}
Upvotes: 3