C ++ std :: moving confusion

I am confused about what happens in the following code snippet. Is move really necessary here? What would be the optimal + safe way to return a temporary set?

 set<string> getWords() { set<string> words; for (auto iter = wordIndex.begin(); iter != wordIndex.end(); ++iter) { words.insert(iter->first); } return move(words); } 

My calling code just does set<string> words = foo.getWords()

+4
source share
3 answers

First, the set is not temporary, but local.

Secondly, the correct way to return it is through return words; .

This is not the only way that you allow the optimization of the return value, but in addition, the local variable is also bound to the constructor of the movement of the returned object in the (unusual) case when the copy is not completely excluded. So this is a true triple win scenario.

+6
source

There is no need to use movement. Just return the "words". He will participate in the so-called "profitability optimization".

Section 12.8 of the C ++ 11 standard requires that the move constructor be called (if one exists) when a local variable is returned. Essentially, the compiler will take care of calling std :: move for you.

+3
source

No, explicit move not necessarily the most optimal way to move set . Since set returned by value, the compiler can optimize the value of the name in set , which means that it can leave the copy and directly build the set object at the place of the call where the return value should be stored. Explicit relocation will prevent this.

+2
source

Source: https://habr.com/ru/post/1437086/


All Articles