问题描述
如果我通过 GCC 4.7 快照传递以下代码,它会尝试将 unique_ptr
复制到向量中.
If I pass the following code through my GCC 4.7 snapshot, it tries to copy the unique_ptr
s into the vector.
#include <vector>
#include <memory>
int main() {
using move_only = std::unique_ptr<int>;
std::vector<move_only> v { move_only(), move_only(), move_only() };
}
显然这是行不通的,因为 std::unique_ptr
是不可复制的:
Obviously that cannot work because std::unique_ptr
is not copyable:
错误:使用已删除的函数 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int;_dp = std::default_delete;std::unique_ptr<_Tp, _Dp> = std::unique_ptr]'
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; std::unique_ptr<_Tp, _Dp> = std::unique_ptr]'
GCC 尝试从初始化列表中复制指针是否正确?
Is GCC correct in trying to copy the pointers from the initializer list?
推荐答案
<initializer_list>
在 18.9 中的概要清楚地表明初始化列表的元素总是通过常量引用传递.不幸的是,在当前版本的语言中,似乎没有任何方法可以在初始化列表元素中使用移动语义.
The synopsis of <initializer_list>
in 18.9 makes it reasonably clear that elements of an initializer list are always passed via const-reference. Unfortunately, there does not appear to be any way of using move-semantic in initializer list elements in the current revision of the language.
具体来说,我们有:
typedef const E& reference;
typedef const E& const_reference;
typedef const E* iterator;
typedef const E* const_iterator;
const E* begin() const noexcept; // first element
const E* end() const noexcept; // one past the last element
这篇关于我可以列表初始化仅移动类型的向量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!