简体   繁体   中英

Does C++11 guarantee the local variable in a return statement will be moved rather than copied?

#include <vector>

using namespace std;

struct A
{
    A(const vector<int>&) {}
    A(vector<int>&&) {}
};

A f()
{
    vector<int> coll;
    return A{ coll }; // Which constructor of A will be called as per C++11?
}

int main()
{
    f();
}

Is coll an xvalue in return A{ coll }; ?

Does C++11 guarantee A(vector<int>&&) will be called when f returns?

C++11 does not allow coll to be moved from. It only permits implicit moves in return statements when you do return <identifier> , where <identifier> is the name of a local variable. Any expression more complicated than that will not implicitly move.

And expressions more complex than that will not undergo any form of elision.

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