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

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

我正在试验以下代码:

#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 a2(A());其实是函数声明,而不是对象的声明。看到这个:

My attempt at value initialization is interpreted as a function declaration, and why doesn't A a(()); solve it?

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

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