user11498510
user11498510

Reputation:

how to deep copy a vector of unique_ptr

I have a class Container with a data member.

std::vector< std::unique_ptr<Sum_Function> > Functions;

I want to do a deep copy in my copy constructor , how can i do a deep copy of std::unique_ptr.

Upvotes: 3

Views: 1747

Answers (3)

Jepessen
Jepessen

Reputation: 12415

std::vector<std::unique_ptr<Sum_Function>> copiedFunctions;
std::for_each(Functions.begin(), Functions.end(), [&](std::unique_ptr<Sum_Function> f){
  copiedFunctions.push_back(std::make_unique<Sum_Function>(*f));
}));

This implies that Sum_Function has a copy constructor, of course.

Upvotes: 3

lubgr
lubgr

Reputation: 38287

If Sum_Function is the concrete type that you want to copy:

#include <algorithm>

Container(const Container& other) : Functions(other.Functions.size())
{
   std::transform(other.Functions.cbegin(), other.Functions.cend(), Functions.begin(),
       [](const auto& uPtr){ return uPtr ? std::make_unique<Sum_Function>(*uPtr) : nullptr; });
}

Otherwise (e.g. when Sum_Function is an abstract base class), you need a virtual factory member function Sum_Function::clone() that should be invoked in the lambda.

Upvotes: 3

Kaldrr
Kaldrr

Reputation: 2850

As you can't make a copy of std::unique_ptr, you need to manually copy all the elements, I think the best approach would be std::transform.

std::vector<std::unique_ptr<Sum_Function>> copy;
copy.reserve(Functions.size());

std::transform(Functions.cbegin(), Functions.cend(), std::back_inserter(copy),
               [](const std::unique_ptr<Sum_Function&> ptr) { return std::make_unique<Sum_Function>(*ptr); }
              );

This code assumes that Sum_Function has a copy constructor.

Upvotes: 3

Related Questions