为什么这个移动构造函数不是临时调用rvalue?

时间:2017-12-24 11:23:25

标签: c++ c++11

我有这段代码。我期望用移动构造函数创建d3,因为我传递了一个临时值。

#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;
}

我看到输出为:

constructor
d1:1

copy constructor
d2:2

constructor
d3:1

constructor
move constructor
d4:3

虽然d4是按照我的预期使用移动构造函数构建的,但我不明白为什么d3.x得到值1.看来d3是由默认构造函数构造的?< / p>

0 个答案:

没有答案
相关问题