【问题标题】:C++ move constructor not called [duplicate]C ++移动构造函数未调用[重复]
【发布时间】:2017-11-27 20:54:30
【问题描述】:

在以下(借用)示例中,在我的环境中,从不调用移动构造函数:

#include <iostream>

class MyClass {
  public:
      MyClass()
      {
          std::cout << "default constructor\n";
      }
      MyClass(MyClass& a)
      {
          std::cout << "copy constructor\n";
      }

      MyClass(MyClass&& b)
      {
          std::cout << "move constructor\n";
      } 
};  

void test(MyClass&& temp)
{
    MyClass a(MyClass{}); // calls MOVE constructor as expected
    MyClass b(temp); // calls COPY constructor...  
}

int main()
{
    test(MyClass{});
    return 0;
}

我的输出是: 默认构造函数 默认构造函数 复制构造函数

我使用 XCode 9.1 版,不应该在右值引用上调用移动构造函数吗?我在这里错过了什么?

约翰。

【问题讨论】:

  • MyClass&amp;&amp; temp 实际上是您调用 MyClass b(temp); 时的左值(因为它有名称);为了调用右值构造函数,您需要 move 它 (MyClass b(std::move(temp));)

标签: c++ move-constructor


【解决方案1】:

我在这里错过了什么?

关键是所有有名字的东西都是左值。

表示命名的右值引用本身就是左值和temp from:

void test(MyClass&& temp)

也是左值。所以移动构造函数没有被调用。

如果要调用移动构造函数,请使用std::move

void test(MyClass&& temp)
{
    // ...
    MyClass b(std::move(temp)); // use std::move here 
}

顺便说一句,

 MyClass(MyClass& a)
 {
     std::cout << "copy constructor\n";
 }

不是复制构造函数,因为复制构造函数的形式为:

MyClass(const MyClass& a) { ... }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 2022-11-21
  • 2016-06-20
  • 2012-10-17
  • 1970-01-01
相关资源
最近更新 更多