GnomeSort
GnomeSort

Reputation: 285

Create a copy of objects pointed to by elements of a vector of shared_pointers

I have a class customClass1 with a property that is a std::vector<std::shared_ptr<customClass2>>.

How can I make a copy of a customClass1 object that contains pointers to identical copies of the objects pointed to by the elements of the first std::vector<std::shared_ptr<customClass2>>?

I don't want to simply make copies of the pointers contained in the vector. I want to actually make copies of the objects that the pointers are pointing to, and then have pointers to these new objects stored in my second customClass1 object's vector property.

Upvotes: 0

Views: 1499

Answers (1)

NathanOliver
NathanOliver

Reputation: 181068

What you are going to have to do is iterate through the vector you want to copy and create new shared_ptrs that have the same value as the underlying object in the vector you are copying from. You can do that with:

std::vector<std::shared_ptr<customClass2>> original; // this has the data to copy
std::vector<std::shared_ptr<customClass2>> copy;
copy.reserve(original.size()); // prevent reallocations

for (const auto& e : original)
    copy.push_back(std::make_shared<customClass2>(*e));

If you are dealing with a polymorphic type this will slice the object as you have a pointer to the base so only the bass part will be copied. If you are working with a polymorphic type you can create a virtual clone function and use clone() to copy the object. For more on this see What is a “virtual constructor”? on the isocpp.org FAQ

Upvotes: 8

Related Questions