【问题标题】:Automatic generation of the move constructor自动生成移动构造函数
【发布时间】:2013-02-20 04:22:45
【问题描述】:
#include <iostream>

using namespace std;

struct A
{
    A() {}
    A(const A &a) {
        cout << "copy constructor" << endl;
    }
    A& operator=(const A &a) {
        cout << "assigment operator" << endl;
    }
    A(A &&a) {
        cout << "move" << endl;
    }
    A& operator=(A &&a) {
        cout << "move" << endl;
    }
};

struct B {
    A a;
};

B func() {
    B b;
    return b;
}
int main() {
    B b = func();
}

这会打印“复制构造函数”。

对于 B 类,移动构造函数和移动赋值运算符应该是自动生成的,对吗?但是为什么使用A类的拷贝构造函数而不是移动构造函数呢?

【问题讨论】:

  • 我认为您需要为 B 类 (B::B(A&amp;&amp; _a) : a(_a) { }) 创建显式-隐式构造函数,但我不确定,所以将其发布为评论。我认为可能还需要std::forward,但我还是将它留给 C++ 大师。

标签: c++ c++11 move-semantics


【解决方案1】:

对我来说,它根本不打印任何东西,因为复制/移动已被省略。但是,如果我通过以下方式阻止 RVO:

extern bool choice;

B func() {
    B b1, b2;
    if (choice)
      return b1;
    return b2;
}

然后打印:

move

可能是你的编译器还没有实现移动成员的自动生成。

【讨论】:

  • +1。你打败了我;这看起来像是提问者的 C++11 编译器中的一个缺陷(错误)。
  • 我用的是visual studio 2010,可能还没有实现
  • 很有可能。该编译器在委员会解决是否隐式生成移动成员的问题之前发布。
猜你喜欢
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
  • 2012-11-09
  • 2012-03-08
  • 2011-08-21
  • 2016-12-16
  • 1970-01-01
  • 2019-04-16
相关资源
最近更新 更多