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