我有以下代码:
#include <iostream>
class B{
public:
//this should all be generated by default but
//throwing them in here just to be sure
B() = default;
B(const B& b) = default;
B& operator=(const B& b) = default;
B(B&& b) = default;
B& operator=(B&& b) = default;
};
class A {
public:
A(B x) : x_(x) {}
A(const A& a) = delete;
A& operator=(const A& a) = delete;
//move operations should be generated by compiler?
private:
B x_;
};
int main() {
A a = A(B());
}
我希望可以编译它,并使用它的move构造函数创建一个
A
,但是这样做失败,并显示以下消息:当然,添加 move 操作并用默认关键字标记它们可以消除此问题。我是否应该假定 move 操作不是由编译器生成的,为什么? delete关键字是否将这些方法标记为用户实现的方法,因此不会生成任何 move 操作?为什么偏爱使用复制构造函数呢?我正在使用gcc进行编译。
最佳答案
如果您提供复制构造函数/operator=
的实现,则默认情况下将不再生成 move 操作。如果需要它们,则需要明确告知您要这样做。
根据cppreference:
这是针对这种情况的有用图表:
attribution