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

偶尔善良 提交于 2019-12-13 13:11:20

问题


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?


回答1:


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++.




回答2:


This looks like a way to go:

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 any warning from gcc and clang, and valgrind doesn't report any memory leak while playing around with copies and vectors.




回答3:


It sounds to me as if boost::ptr_container would serve your needs here. http://www.boost.org/doc/libs/1_55_0/libs/ptr_container/doc/ptr_container.html



来源:https://stackoverflow.com/questions/23535719/add-a-deep-copy-ctor-to-stdunique-ptrmy-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!