is there any difference between static cast to rvalue reference and std::move
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.
In C++11, T&&
is an rvalue reference. They behave like lvalue references from C++ 98/03. Their goal - to be a candidate for moving. In C++98 this construct can appear in reference collapsing.
std::move
- turn expression into an rvalue. It could have been called rvalue_cast, but wasn't.
Explicit cast to type T&&
is possible in principle. The official standard costs some money, but in the ISO/IEC 14882:2011 draft there's this:
5.2.9 Static cast
8)
The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) conversions are applied to the operand....
From a practical point of view, it is more convenient to use std::move
.
Consider this example:
#include <stdio.h>
#include <utility>
class A
{
public:
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
}
For me, the first approach is:
- more convenient (should you perform
static_cast
toconst A&&
, or toA&&
?) - more explicitly (I can use search in text editor to find
std::move
in the project) - less error-prone.