保证移动前复制
Guarantee of copying before moving
对于给定的示例代码:
struct some_struct_t {
std::string key;
// other fields;
}
std::unordered_map<std::string, TSomeStruct> hashmap;
some_struct_t some_struct;
// filling some_struct
hashmap[some_struct.key] = std::move(some_struct);
是否可以保证some_struct.key
将作为hashmap
的关键,将some_struct
移至hashmap
?
是否可以保证
some_struct.key
作为hashmap的关键 移动某些_ struct?
是。
std::move()
实际上没有移动。它更像是从lvalue参考到rvalue参考的演员。正确的分配过程中发生了实际移动(如果任何 1 ),则在评估分配运算符的左侧后进行了测序。
1 如果分配解析为移动分配或通过值接收其参数并使用MOVE-CONSTRUCTOR。
可以将表达式改写为:
hashmap.operator[](some_struct.key).operator=(std::move(some_struct));
因此,第一个呼叫将为operator[]
,而不是operator=
相关文章:
- 当有分配器意识的容器被复制/移动时,反弹分配器是否被复制/移走
- std::元组分配和复制/移动异常保证
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- 在临时将成员带出时省略复制/移动
- 是否可以避免在以下代码中复制/移动构造函数的需要?
- 默认复制/移动构造函数时 GDB 中的奇怪行为
- 返回 *&object 时是否允许复制/移动省略?
- 删除复制构造函数是否也会删除默认的复制/移动运算符?
- 用于删除复制/移动分配运算符的有效签名
- 复制 elision/RVO 会导致从同一对象复制/移动吗?
- 意外缺少隐式声明的复制/移动构造函数
- 是否可以传递具有捕获的不可复制(移动)值的 lambda
- CRTP 和复制/移动赋值/构造函数继承
- C++复制/移动构造函数和赋值运算符
- 覆盖复制/移动分配超载时,我是否需要删除当前的成员数据
- 为什么编译器在有模板构造函数时生成复制/移动构造函数
- C++:使用引用和值解压缩元组,而无需复制/移动太多
- 从C++中的基类继承复制/移动构造函数作为构造函数
- 初始化 std::数组而不复制/移动元素
- 是否允许复制/移动省略使使用已删除函数的程序格式正确?