将深层复制ctor添加到std :: unique_ptr< my_type> [英] Add a deep copy ctor to std::unique_ptr<my_type>

查看:158
本文介绍了将深层复制ctor添加到std :: unique_ptr< my_type>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 std :: vector 中存储一些 std :: unique_ptr< my_type> 。由于 my_type 提供了一个 clone()方法,可以非常简单地创建 my_type * 。关键是如何扩展 std :: unique_ptr 保留所有的功能,同时添加copy ctor和赋值运算符。遗产? Templace专业化?

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?

推荐答案

这看起来像一条路:

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; }
};

它编译时没有gcc和clang的任何警告,valgrind不报告任何内存泄漏,周围有副本和向量。

It compiles without any warning from gcc and clang, and valgrind doesn't report any memory leak while playing around with copies and vectors.

这篇关于将深层复制ctor添加到std :: unique_ptr&lt; my_type&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆