lundi 20 avril 2015

Move constructor not called

After trying to write an example regaurding move constructors, i ran into the following code:

#include <utility>
#include <iostream>

using namespace std;

class Data
{
public:
    Data()
    : x (3)
    {
        cout << "Data()" << endl;
    }
    Data(Data&&)
    : x(4)
    {
        cout << "Data(&&)" << endl;
    }

int x;
};

int main()
{
    Data a;
    Data b (std::move(a));
    cout << b.x << endl;
    return 0;
}

why is the move constructor not called here? The program prints:

Data()

3

What i'm finding even wierder is that by adding a copy constructor, suddenly, it does call the move constructor...

    Data(const Data&)
    : x(2)
    {
        cout << "Data(copy)" << endl;
    }

And now it will print

Data(&&)

4

Aucun commentaire:

Enregistrer un commentaire