【问题标题】:std::vector<std::unique_ptr<int> > does not compilestd::vector<std::unique_ptr<int> > 不编译
【发布时间】:2014-05-12 08:50:10
【问题描述】:

当我声明一个 unique_ptr 的向量时,我得到了这种错误:

d:\qt\mingw64\include\c++\4.8.0\bits\stl_construct.h:75: error:
use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(
const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'

这看起来像是创建没有复制构造函数的对象容器的经典错误。

但是,由于 c++11 移动语义,我能找到的所有东西都记录了 unique_ptrs 的标准容器。

我正在使用 MinGW-gcc 64 位编译,使用 -std=gnu++11。

只有c++11支持,gnu++11不支持吗?

谢谢

【问题讨论】:

  • 你为什么不试试c++11?
  • 4.8.0 它不符合 C+11,任何从 4.8.1 开始的版本都是
  • 向我们展示一个演示您的确切错误的最小示例程序,以便我们尝试。
  • 我刚刚发现 std::vector<:unique_ptr>> 被声明为类中的成员变量。由于该类有一个复制构造函数,如果我理解正确,这就是问题所在。

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


【解决方案1】:

以下将使用 C++11 编译。

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

int main()
{
    std::vector<std::unique_ptr<int> > asdf;
    return 0;
}

【讨论】:

    【解决方案2】:

    问题不在于std::vector&lt;std::unique_ptr&lt;int&gt; &gt; 本身,而是在可复制类中声明的该类型的成员变量。由于该类的默认拷贝构造函数调用了std::vector的拷贝构造函数,而后者又调用了std::unique_ptr的默认构造函数,后者被删除,编译失败。

    std::vector&lt;std::unique_ptr&lt;int&gt; &gt; 可以很好地编译为函数中的局部变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-17
      • 2015-07-23
      • 1970-01-01
      • 2019-11-07
      • 2018-02-02
      • 2015-10-11
      • 1970-01-01
      • 2020-01-26
      相关资源
      最近更新 更多