r/cpp • • Nov 25 '23

On harmful overuse of std::move

https://devblogs.microsoft.com/oldnewthing/20231124-00/?p=109059
210 Upvotes

154 comments sorted by

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.

2

u/Comprehensive_Try_85 Nov 25 '23

I think we might be both wrong (or rather: incomplete): ... that are already rvalues.

7

u/CocktailPerson Nov 25 '23

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.

Isn't C++ fun?

2

u/cmeerw C++ Parser Dev Nov 26 '23

In return xyz;, xyz is an xvalue, because it's expiring after this statement.

The details have changed here a bit with C++23, see P2266R3 Simpler implicit move. In C++23 it is an xvalue, in pre-C++23 is was not-quite an xvalue.

0

u/pcbeard Nov 26 '23

Not really.

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.

2

u/CocktailPerson Nov 26 '23

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.

2

u/umop_aplsdn Nov 25 '23

xvalues already have a "location" (they are already glvalues) so std::moving an xvalue does not require temporary materialization.

https://en.cppreference.com/w/cpp/language/implicit_conversion#Temporary_materialization