usage - static_cast in c++ geeksforgeeks

is there any difference between static cast to rvalue reference and std::move (2)

The description for static cast says

If new_type is an rvalue reference type, static_cast converts the value of expression to xvalue. This type of static_cast is used to implement move semantics in std::move.(since C++11)

Does this confirm that the following are equivalent ?


X x1;
X x2 = static_cast<X&&>(x1); 


X x1;
X x2 = std::move(x1);

T&& In C++11 is rValue reference. They behave like lvalue reference from C++ 98,03. Their goal - to be a candidate for moving. In C++98 such construction can be appear in refrence collapsing

std::move - turns expression in rvalue. It could be called rvalue_cast, but such keyword is not exist.

Explicit cast to type T&& possible in principle. Real standart cost some money, but in draft of the ISO/IEC 14882:2011 There is exist such info

5.2.9 Static cast


The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) conversions are applied to the operand....

From practical point of view it is more convenient to use std::move. Imagine such example:

#include <stdio.h>
#include <utility>

class A
A () {printf ("A ()" "\n");}
A (const A &) {printf ("A (&)" "\n");}
A (A &&) {printf ("A (&&)" "\n");}
A (const A &&) {printf ("A (const &&)" "\n");}
~ A () {printf ("~ A ()" "\n");}

int main ()
const A obj;
A obj2 (std::move (obj)); // 1-st approach
A obj3 (static_cast <const A&&> (obj));  // 2-nd approach

As for me 1-st approach is

  • more convenient (should you perform static_cast to const A&&, or to A&& ?)
  • more explicitly (I can use search in text-editor to find std::move in project)
  • less error-prone when software developer write code

Yes there is a very important difference: std::move documents what you want to do. In addition the cast is prone to writing errors like a forgotten & or wrong type X.

As it can be seen, std::move is even less to type.