Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a deep copy ctor to std::unique_ptr<my_type>

I would like to store some std::unique_ptr<my_type> into a std::vector. Since my_type provides a clone() method it's quite straightforward to make deep copies of my_type *. The point is how to extend std::unique_ptr preserving all its functionalities while adding the copy ctor and the assignment operator. Inheritance? Templace specialization? Could you please provide a code snippet?

like image 277
DarioP Avatar asked May 08 '14 07:05

DarioP


1 Answers

The purpose of std::unique_ptr is for it to be unique i.e. it shouldn't be copyable. That's why they made it to be move-only. It is used for representing unique ownership.

If you want to make a deep copy then let your copy constructor do its work, that's what it's for.

std::unique_ptr<my_type> ptr1{new my_type{}};      // Lets say you have this.

std::unique_ptr<my_type> ptr2{new my_type{*ptr1}}; // Make deep copy using copy ctor.

The purpose of the copy ctor is to make a deep copy. You don't need a clone method in C++.

like image 58
Felix Glas Avatar answered Oct 06 '22 00:10

Felix Glas