【发布时间】: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&& _a) : a(_a) { }) 创建显式-隐式构造函数,但我不确定,所以将其发布为评论。我认为可能还需要std::forward,但我还是将它留给 C++ 大师。
标签: c++ c++11 move-semantics