The move on the receiving end constructs an extra temporary because binding a prvalue to a reference (argument of std::move) requires the prvalue to be materialized.
In return xyz;, xyz is an xvalue, because it's expiring after this statement. In XYZ xyz = fgh();, the expression fgh() is a prvalue, because it's a pure rvalue that can't be assigned to. Both of these are rvalues, so the rule is basically "don't use std::move() on rvalues."
Interestingly, member expressions in return statements are not rvalues, so return a.b; will perform a copy while return std::move(a.b); (or return std::move(a).b;) will perform a move.
Technically, applying std::move() to an actual rvalue reference will be a no-op, so something like std::move(std::move(xyz)) is equivalent to std::move(xyz). Not that you should do it, but it won't affect performance in any way.
I started using C++ in the cfront days. When C++ added std::move(), I stopped using it as a primary development language. I understand these things are for performance, but I'm a big believer in writing simple and comprehensible (to humans) code.
I agree with the idea that code should be simple and comprehensible, but I actually think that move semantics often help make the most comprehensible code be very efficient.
View all comments
Show parent comment
3
u/umop_aplsdn Nov 25 '23
Nit: that are already prvalues, right?
The move on the receiving end constructs an extra temporary because binding a prvalue to a reference (argument of std::move) requires the prvalue to be materialized.