简体   繁体   中英

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.

What you are going to have to do is iterate through the vector you want to copy and create new shared_ptr s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM