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_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?
推荐答案
<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
这篇关于我可以列表初始化仅移动类型的向量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以列表初始化仅移动类型的向量吗?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
