In recent discussions around the use of std::move in C++, questions have arisen regarding its potential overuse and the compiler's treatment of its return values. Addressing concerns raised by developers like Jonathan Duncan, this article delves into the nuances of std::move
, examining whether its current implementation aligns with compiler optimizations and proposing potential enhancements for more efficient code generation.
More on harmful overuse of
std::move
by Raymond Chen
From the article:
Some time ago, I wrote about harmful overuse of
std::
. Jonathan Duncan asked,move Is there some side-effect or other reason I can’t see return std::move(name); case isn’t possible to elide? Or is this just a case of the standards missing an opportunity and compilers being bound to obey the standards?
In the statement
return std::move(name);
, what the compiler sees isreturn f(...);
wheref(...)
is some mysterious function call that returns an rvalue. For all it knows, you could have writtenreturn object.
, which is also a mysterious function call that returns an rvalue. There is nothing in the expressionoptional_name(). value(); std::move(name)
that says, “Trust me, this rvalue that I return is an rvalue of a local variable from this very function!”Now, you might say, “Sure, the compiler doesn’t know that, but what if we made it know that?” Make the function
std::move
a magic function, one of the special cases where the core language is in cahoots with the standard library.This sort of in-cahoots-ness is not unheard of. For example, the compiler has special understanding of
std::launder
, so that it won’t value-propagate memory values across it, and the compiler has special understanding of memory barriers, so that it won’t optimize loads and stores across them.
Add a Comment
Comments are closed.