Search code examples
c++operator-overloadingmove-semanticsrvalue-referenceperfect-forwarding

Shorthand for std::move


Would it be a bad practice for some class S to overload unary operator + (or maybe operator * for non-pointer-like classes) as following?

struct S { S && operator + () & noexcept { return std::move(*this); } };

The goal it to invent shorthand for std::move.

S a;
S b = +a;
// instead of
S c = std::move(a);

Say I have a project with plenty of different classes, which intensively uses move-semantics. All the classes not mimics any arithmetical counterparts.


Solution

  • It is objectively bad practice to do such a thing. std::move() is the standard provided, well-understood way of casting to an rvalue (specifically xvalue). Anybody who sees std::move(a) either knows exactly what it does - or doesn't understand move semantics anyway (and if they don't, std::move is pretty easy to Google to learn about).

    Seeing +a does not have any meaning without having to look it up first. Even worse, there is an expected meaning of what unary + does for many types - which has nothing to do with move semantics! (e.g. Is a a char getting promoted to int? Is it a no-capture lambda getting converted to a function pointer?) All for just saving 10 characters? Not to mention that you'd have to implement this operator+ for every type, and you don't have to implement std::move() at all. That is a very poor trade-off.