mercredi 26 août 2015

C++11: Is using std::move only safe on temporary objects?

In my code, I have something like this:

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

As you can see, I'm using std::move on an object of type deduced to unordered_map<string, string>&, which is obviously not unordered_map<string, string>&&. Still, I know for sure that because rawEntities goes out of scope after the for loop, its elements (the string->string maps) will never be used again. So I'm figuring that it's safe to steal (move) its elements data because they won't be used again.

When I run the program, it seems to work. But is this bad practice / an anti-pattern, and particularly, does the standard guarantee it is safe?

Aucun commentaire:

Enregistrer un commentaire