I'm confused as to what is going on in the following code snippet. Is move
really necessary here? What would be the most optimal + safe way of returning the 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 simply does set<string> words = foo.getWords()
First off, the set is not temporary, but local.
Second, the correct way to return it is via return words;
.
Not only is this the only way you allow for return-value optimization, but moreover, the local variable will also bind to the move constructor of the returned object in the (unusual) case where the copy is not elided altogether. So it's a true triple-win scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With