我有这段代码。我还希望d3通过move构造函数来创建,因为我传递了一个rvalue临时对象。
#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;
}
Run Code Online (Sandbox Code Playgroud)
我看到的输出为:
constructor
d1:1
copy constructor
d2:2
constructor
d3:1
constructor
move constructor
d4:3
Run Code Online (Sandbox Code Playgroud)
虽然d4是按预期的那样使用move构造函数构造的,但我不明白为什么会d3.x得到值1。似乎d3是由默认构造函数构造的?
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |