Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 866
xmllmx Avatar asked Feb 24 '17 16:02

xmllmx


People also ask

Do you need to return std :: move?

When returning a named local variable or a temporary expression directly, you should avoid the explicit std::move . The compiler must (and will in the future) move automatically in those cases, and adding std::move might affect other optimizations.

Does returning an object copy it C++?

commercial-grade C++ compilers won't do that: the return statement will directly construct x itself. Not a copy of x, not a pointer to x, not a reference to x, but x itself.

What type does std :: move return?

In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.

Does STD copy move?

std::move is actually just a request to move and if the type of the object has not a move constructor/assign-operator defined or generated the move operation will fall back to a copy.


1 Answers

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.

like image 121
Nicol Bolas Avatar answered Nov 11 '22 22:11

Nicol Bolas