Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between type casting and using std::move()?

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!

like image 912
Dean Seo Avatar asked Sep 22 '11 02:09

Dean Seo


2 Answers

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.

like image 136
Nicol Bolas Avatar answered Oct 05 '22 06:10

Nicol Bolas


There is no difference in functionality, but there is a difference in readability.

Just as while loops are preferred to gotos, 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.

like image 29
Mankarse Avatar answered Oct 05 '22 07:10

Mankarse