简体   繁体   中英

c++ std::move confusion

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.

There's no need to use move here. Simply return "words". It will participate in the so-called "return value optimization".

Section 12.8 in the C++11 standard requires the move constructor to be called (if it exists) in the case where a local variable is returned. In essence, the compiler will take care of calling std::move for you.

No, the explicit move is not necessarily the most optimal way to move the set . Since the set is being returned by value, the compiler may perform named return value optimization on the set , meaning it may elide the copy and directly construct the set in-place at the call-site where the return value is to be stored. Explicit moving will inhibit this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM