我可以列表初始化一个只移动类型的向量吗? [英] Can I list-initialize a vector of move-only type?
问题描述
如果我通过我的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?
推荐答案
18.9中的< initializer_list>
使得相当清楚的是初始化器列表的元素总是通过const引用传递。不幸的是,在语言的当前版本中,似乎没有任何方式在初始化列表元素中使用移动语义。
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
这篇关于我可以列表初始化一个只移动类型的向量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!