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

I would like to save some std::unique_ptr<my_type> in std::vector . Since my_type provides the clone() method, just make deep copies of my_type * . The point is how to extend std::unique_ptr , retaining all its functionality, adding a copy of ctor and an assignment operator. Inheritance? Thematic specialization? Could you provide a code snippet?

+3
c ++ copy-constructor c ++ 11 deep-copy unique-ptr
source share
3 answers

It looks like a way:

 struct my_type_ptr: public std::unique_ptr<my_type,std::default_delete<my_type>>{ using unique_ptr::unique_ptr; //inheriting constructors //adding copy ctor and assigment operator my_type_ptr(const my_type_ptr & o): unique_ptr<my_type,std::default_delete<my_type>>() { reset( o ? o->clone() : nullptr); } my_type_ptr& operator=(const my_type_ptr & o) { reset( o ? o->clone() : nullptr); return *this; } }; 

It compiles without warning from gcc and clang, and valgrind does not report a memory leak while playing with copies and vectors.

+2
source share

The purpose of std::unique_ptr is to make it unique, that is, it should not be copied. That's why they did it just for the move. It is used to represent a unique property.

If you want to make a deep copy, then let your copy designer do the work that he is 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 a ctor copy is to make a deep copy. You do not need the clone method in C ++.

+4
source share

It seems to me that boost :: ptr_container will serve your needs here. http://www.boost.org/doc/libs/1_55_0/libs/ptr_container/doc/ptr_container.html

+1
source share

All Articles