Why isn't this move constructor called temporary?

I have this piece of code. I expected to d3be created using the move constructor since I passed the temporary rvalue value.

#include <iostream>

using namespace std;

struct Data {
    Data(): x(1)
    {
        cout << "constructor" << endl;
    }

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

    Data(Data&& original): x(3)
    {
        cout << "move constructor" << endl;
    }

    int x;
};

int main() {
    Data d1; // constructor
    cout << "d1:" << d1.x << endl << endl;

    Data d2(d1); // copy constructor
    cout << "d2:" << d2.x << endl << endl;

    Data d3(Data{}); // move constructor?
    cout << "d3:" << d3.x << endl << endl;

    Data d4(move(Data{})); // move constructor?
    cout << "d4:" << d4.x << endl << endl;

    return 0;
}

I saw the result as:

constructor
d1:1

copy constructor
d2:2

constructor
d3:1

constructor
move constructor
d4:3

Although d4created with the move constructor, as I expected, I don’t understand why I d3.xgot the value 1. It seems that it was d3built by the default constructor?

+4
source share

Source: https://habr.com/ru/post/1691302/


All Articles