移动前复制保证

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 移动到 hashmap 之前 some_struct.key 将作为 hashmap 的密钥?

表达式可以重写为:

hashmap.operator[](some_struct.key).operator=(std::move(some_struct));

所以第一个电话是 operator[] 然后是 operator=

Is there a guarantee that some_struct.key will be got as a key for hashmap before moving some_struct?

是的。

std::move()实际上并没有移动。它更像是从左值引用到右值引用的转换。实际移动(如果有1)发生在正确的赋值过程中,在评估赋值运算符的左侧后排序。

1 如果赋值解析为移动赋值或通过值接收其参数并利用移动构造函数的复制赋值,则会发生移动。