c++ - unique_ptr 的 deque vector 的编译器错误

标签 c++ c++11

以下代码无法在 gcc 5.3 上编译,编译器错误提示 unique_ptr 的复制构造函数以某种方式被调用。有人可以解释为什么会这样吗?

#include <iostream>
#include <memory>
#include <deque>

using Foo = std::deque<std::unique_ptr<int>>;                                   


void foo() {                                                                    
  std::vector<Foo> a;                                                           
  a.emplace_back();   // this fails to compile                                                             
}

编译错误中的关键行是:

gcc-4.9.2/include/c++/4.9.2/bits/stl_construct.h:75:7: 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>]’ { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }

最佳答案

  • vector::emplace_back需要处理重新分配。
  • 关于 vector重新分配,现有元素移动,如果有的话

    • 它们不能被复制(由 std::is_copy_constructible 确定);或
    • 他们的移动构造函数是noexcept .

    否则它们被复制。这是为了维护强大的异常安全保证。

  • std::deque<std::unique_ptr<int>>的移动构造函数不是 noexcept (根据具体实现,可能需要分配内存)。
  • std::deque<std::unique_ptr<int>>可以根据std::is_copy_constructible复制,因为它只检查是否存在具有正确签名的构造函数,而不检查所述构造函数的主体是否会实际编译。
  • vector::emplace_back因此试图复制它。
  • 编译器崩溃了。

关于c++ - unique_ptr 的 deque vector 的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367905/

相关文章:

c++ - clang++ (3.3/Xcode) 中 std::function 的定义在哪里

c++ - 原型(prototype)模式 C++ 中的智能指针

c++ - getaddrinfo() 只返回::1 作为 IPV6 地址,

c++ - Digia 购买后现在的 Qt 许可证

c++ - std::regex_replace 仅第一次出现

c++ - CPP 函数无法获得正确的输出

visual-studio-2010 - 函数声明中的 static_assert

c++ - Boost random::discrete_distribution 构建后如何改变权重?

C++ 快速排序索引 0 返回 -842150451

c++ - 多次使用 std::async 对小任务性能友好吗?