【发布时间】:2015-11-21 01:59:09
【问题描述】:
在我的代码中,我有这样的东西:
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
如您所见,我在推断为unordered_map<string, string>& 的类型对象上使用std::move,这显然不是unordered_map<string, string>&&。不过,我确信因为rawEntities 在for 循环之后超出范围,它的元素(字符串-> 字符串映射)将永远不会被再次使用。所以我认为窃取(移动)其元素数据是安全的,因为它们不会被再次使用。
当我运行程序时,它似乎可以工作。但是这种不好的做法/反模式,特别是标准是否保证它是安全的?
【问题讨论】:
-
只看你的问题标题,答案是临时对象(根据定义)是纯右值,而
std::move只是一个演员表,在这种情况下这是不必要的。