#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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With