C ++ 11: Uses std :: move only safe for 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 use std::move for an object of type displayed on unordered_map<string, string>& , which obviously is not unordered_map<string, string>&& . However, I know for sure that since rawEntities goes beyond the scope after the for loop, its elements (strings-> string charts) will never be used again. Therefore, I believe it is safe to steal (move) the data of my elements because they will no longer be used.

When I run the program, it works. But is this bad practice / anti-pattern, and in particular, the standard warranty is safe?

+8
c ++ c ++ 11 move lvalue
source share
2 answers

On the contrary. Using std::move for temporary objects is pointless. They are already values ​​of R and will be displayed as references to the R-value during the transfer of functions. The whole point of std::move is to turn L-values ​​into references to an R-value so that they can be moved from.

So, I believe it is safe to steal (move) the data of your elements because they will no longer be used.

Yes, that's right.

+13
source share

In general, temporary objects do not have a name and already have r / values . std::move is not really applicable, as it is not specified.

When is std::move applied? Whenever an object expires and is no longer required. This is what std::move does, it distinguishes the category of values ​​in such a way that it can be transferred from.

This is an interesting precedent - the theft of (filtered) container contents, not the entire container.

Given that the contents of vector not needed after the for loop completes , then yes, it will work as expected .

+3
source share

All Articles