gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:33:31 26 4
gpt4 key购买 nike

以下代码无法在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com