【问题标题】:C++ : Why is move constructor not getting called? [duplicate]C++:为什么移动构造函数没有被调用? [复制]
【发布时间】: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(); 中的移动(或复制)构造 - 所有这些都将使用 @ 初始化 a2 987654329@ 的默认构造函数。没有临时创建、复制、移动或分配。

标签: c++ move-constructor


【解决方案1】:

因为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())));

【讨论】:

  • A a2(A{});(如果未省略移动构造函数)。
  • 请注意,A a2 = A();A a2(A{});(或类似 A a2 = A(A(A())); 的东西都不会在 C++17 中调用移动构造函数。临时对象永远不会实现。请参阅 timsong-cpp.github.io/cppwp/n4659/dcl.init#17.6.1
猜你喜欢
  • 2018-02-04
  • 2016-07-12
  • 2012-11-16
  • 1970-01-01
  • 2014-01-24
  • 2011-04-18
相关资源
最近更新 更多