【问题标题】:unique_ptr with vector: error: call to implicitly-deleted copy constructor of XXX带有向量的 unique_ptr:错误:调用 XXX 的隐式删除的复制构造函数
【发布时间】:2017-04-14 04:41:51
【问题描述】:

我想管理一个二维数组如下:

std::vector<std::unique_ptr<int []>> vec(5, nullptr);
vec[0] = std::make_unique<int []>(3);
vec[1] = std::make_unique<int []>(4);
...

但是我得到一个错误:

错误:调用 'std::__1::unique_ptr >'的隐式删除复制构造函数

【问题讨论】:

  • 你不做std::vector&lt;std::vector&lt;int&gt;&gt;有什么原因吗?
  • @Galik 没有。但我只需要一个固定大小的数组,所以我使用原始数组。

标签: c++ c++11 vector unique-ptr


【解决方案1】:

我认为问题出在您的vector constructor call2:填充构造函数):

std::vector<std::unique_ptr<int []>> vec(5, nullptr);

在这里,您实际上是在调用vector(size_t(5), std::unique_ptr&lt;int[]&gt;(nullptr))。请注意,这会创建一个 std::unique_ptr 的临时实例,从您的 nullptr 参数隐式转换/构造。然后 vector 构造函数应该复制你传递给它的这个值n 次以填充容器;因为你不能复制任何unique_ptr(甚至是一个空值),你会从该构造函数的代码中得到你的编译器错误。

如果您要立即替换那些初始 nullptr 值,您应该只构建一个空的 vectorpush_back 新元素:

std::vector<std::unique_ptr<int []>> vec; // default constructor
vec.push_back(std::make_unique<int []>(3)); // push the elements (only uses the move
vec.push_back(std::make_unique<int []>(4)); // constructor of the temporary)
...

要使用一些空值初始化vector,请省略第二个参数:

std::vector<std::unique_ptr<int []>> vec(5);

这将使用default constructor 构造每个unique_ptr,不需要任何复制。

【讨论】:

    【解决方案2】:
    std::vector<std::unique_ptr<int []>> vec(5, nullptr);
    

    此行复制构造 5 std::unique_ptr&lt;int []&gt; 从临时构造 nullptr。这是违法的。

    我想你想要这个:

    std::vector<std::unique_ptr<int []>> vec;
    vec.reserve(5);
    vec.push_back(std::make_unique<int []>(std::size_t(3)));
    

    如果你真的想要一个有 5 个 nullptr 的向量,这里是解决方案:

    std::vector<std::unique_ptr<int []>> vec(5);
    vec[0] = std::make_unique<int []>(std::size_t(3));
    

    【讨论】:

      【解决方案3】:

      您将在预期数组的位置插入整数元素。

      【讨论】:

      • 你确定吗?我不这么认为。
      • 您定义了一个向量,该向量接收数组 int[] 的 unique_ptr,当您使用 vec[0] 时,它需要一个 int[] 变量。
      猜你喜欢
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 2016-09-11
      相关资源
      最近更新 更多