Can I list-initialize a vector of move-only type?(我可以列出初始化只移动类型的向量吗?)
问题描述
如果我通过我的 GCC 4.7 快照传递以下代码,它会尝试将 unique_ptr
s 复制到向量中.
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-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
这篇关于我可以列出初始化只移动类型的向量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以列出初始化只移动类型的向量吗?


基础教程推荐
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 设计字符串本地化的最佳方法 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++,'if' 表达式中的变量声明 2021-01-01