Search code examples
c++c++11move-semanticsrvalue-referencervo

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?


Solution

  • 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.