I am just a bit curious about the new function std::move() that has just been added into the newest C++ standard.
Finished reading an article about it and found out that the function's definition is
namespace std {
template <class T>
inline typename remove_reference<T>::type&& move(T&& x)
{
return x;
}
}
This seems like it doesn't have any difference between calling std::move and using casting.
For example here,
class NPC{
int m_number1;
int m_number2;
public:
NPC() : m_number1(1), m_number2(2) {
cout << "NPC Constructor called!" << endl;
}
NPC(NPC&& _npc) : m_number1(_npc.m_number1), m_number2(_npc.m_number2) {
_npc.m_number1 = 0;
_npc.m_number2 = 0;
cout << "NPC Move Constructor called!" << endl;
}
};
int main() {
NPC n1;
NPC n2 = std::move(n1);
cout << "----------------" << endl;
NPC n3;
NPC n4 = (NPC&&)n3;
return 0;
}
Is it right to think that there is basically no difference? Well, I am pretty much sure that I am right but also know that being too confident always backfires.
Thanks in advance!
std::move
is defined as a specialized cast:
static_cast<typename remove_reference<T>::type&&>(t)
You could do this if you really want. But it would be much shorter and obvious to everyone what you're doing if you just use std::move
. The rules around && casting are weird, so it's best to just use move
and forward
when that's what you mean.
There is no difference in functionality, but there is a difference in readability.
Just as while
loops are preferred to goto
s, and C++ style casts are preferred to C style casts, std::move
is preferred to casting because it is a less general tool, and so it is easier to understand what it is doing without needing investigate the structure of the code any further.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With