我可以列出初始化只移动类型的向量吗? [英] Can I list-initialize a vector of move-only type?

查看:45
本文介绍了我可以列出初始化只移动类型的向量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我通过我的 GCC 4.7 快照传递以下代码,它会尝试将 unique_ptrs 复制到向量中.

If I pass the following code through my GCC 4.7 snapshot, it tries to copy the unique_ptrs 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-reference 传递.不幸的是,在当前版本的语言中,似乎没有任何方法可以在初始化列表元素中使用移动语义.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆