C++ 11:在临时对象上使用std :: move只能安全吗?

bom*_*bax 10 c++ move lvalue c++11

在我的代码中,我有这样的事情:

unordered_multimap<string, unordered_map<string, string> > mEntities;
...
vector<unordered_map<string, string> > rawEntities;
if (qi::phrase_parse(&buf[0], (&buf[0]) + buf.size(), EntityParser<char*>(), qi::space, rawEntities)) {
    for (auto &propGroup : rawEntities) {
        auto search = propGroup.find("classname");
        if (search != propGroup.end()) {
            // is stealing propGroup safe???
            mEntities.emplace(search->second, std::move(propGroup)); 
        }
    }
}
// rawEntities goes out of scope here
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我正在使用std::move推导出的类型的对象unordered_map<string, string>&,这显然不是unordered_map<string, string>&&.尽管如此,我确信因为rawEntitiesfor循环之后超出范围,其元素(字符串 - >字符串映射)将永远不会再次使用.所以我认为窃取(移动)其元素数据是安全的,因为它们不会被再次使用.

当我运行程序时,它似乎工作.但这是不好的做法/反模式,特别是,标准是否保证它是安全的?

Ben*_*ley 16

反之.std::move在临时对象上使用是没有意义的.它们已经是R值,并且在传递给函数时将被推导为R值引用.重点std::move是将L值转换为R值引用,以便它们可以从中移动.

所以我认为窃取(移动)其元素数据是安全的,因为它们不会被再次使用.

是的,这是正确的.