自动生成移动构造函数

时间:2012-08-11 15:20:00

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

#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类的复制构造函数而不是移动构造函数?

1 个答案:

答案 0 :(得分:2)

对我而言,它根本不打印任何内容,因为复制/移动已被删除。但是,如果我用类似的东西阻止RVO:

extern bool choice;

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

然后打印:

move

可能是您的编译器尚未实现移动成员的自动生成。