我遇到了一个非常有趣的情况,我的代码编译通过了,尽管我感到很惊讶,所以我想请你发表一下你的看法。
情况是这样的。我有一个类,其中删除了移动和复制构造函数,并具有用户定义的赋值运算符:
struct A {
A() { }
A(const A&) = delete;
A(A&& ) = delete;
A& operator=(const A& ) { return *this; }
A& operator=(A&& ) { return *this; }
};
我还有另一个类,只有 A
作为成员。在这个类中,我定义了拷贝构造函数,但将移动构造函数保持为默认,并通过调用 swap 函数定义赋值运算符:
class B{
public:
A a;
B()
: a{}
{ }
B(const B&)
: a{}
{ }
B(B&& other) = default;
};
int main() {
B b1;
B b2(std::move(b1)); // compiles??
}
默认移动构造函数为什么有效,考虑到它不能简单地调用移动或复制构造函数A? 我正在使用gcc 4.8.4.