保证移动前复制

Guarantee of copying before moving

本文关键字:复制 移动      更新时间:2023-10-16

对于给定的示例代码:

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=