【发布时间】:2020-01-20 10:18:42
【问题描述】:
我正在试验以下代码:
#include <iostream>
#include <utility>
using namespace std;
class A
{
int data;
public:
A(): data{0}
{
}
A(const A& other)
{
print(other);
}
A(A&& other)
{
print(other);
}
void print(const A& other) const
{
cout << "In print 1" << endl;
}
void print(const A&& other) const
{
cout << "In print 2" << endl;
}
};
int main() {
A a0;
A a1(a0);
A a2(A());
return 0;
}
我期望输出是:
In print 1
In print 1
但是,actual output 是:
In print 1
显然,移动构造函数没有被调用。为什么这样?在a2 的构建过程中,什么被调用?
【问题讨论】:
-
A a3(std::move(a0))
-
如果您在 C++17 中,那么您将不会观察到
A a2(A{});或A a2 = A();中的移动(或复制)构造 - 所有这些都将使用 @ 初始化a2987654329@ 的默认构造函数。没有临时创建、复制、移动或分配。
标签: c++ move-constructor