Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ std::move confusion

Tags:

c++

c++11

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()

like image 790
Victor Parmar Avatar asked Dec 21 '22 15:12

Victor Parmar


1 Answers

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.

like image 112
Kerrek SB Avatar answered Dec 24 '22 00:12

Kerrek SB