C++:为什么不调用移动构造函数?

C++ : Why is move constructor not getting called?

本文关键字:构造函数 移动 调用 为什么不 C++      更新时间:2023-10-16

我正在试验以下代码:

#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

但是,实际输出为:

In print 1

显然,移动构造函数不会被调用。为什么会这样?在a2建设过程中,它的位置叫什么?

因为A a2(A());实际上是函数声明,而不是对象的声明。看到这个:

我对值初始化的尝试被解释为函数声明,为什么 A a((((; 解决它?

如果要查看移动构造函数,请执行以下操作:

A a2((std::move(A())));