在学习的过程std::move
中,我发现了一个奇怪的问题。
如果我只添加一个对完美程序没有任何作用的析构函数,我会得到一个编译错误。
#include <iostream>
using namespace std;
class M {
public:
int database = 0;
M &operator=(M &&other) {
this->database = other.database;
other.database = 0;
return *this;
}
M(M &&other) { *this = std::move(other); }
M(M &m) = default;
M() = default;
~M() { /* free db */ }
};
class B {
public:
M shouldMove;
//~B(){} //<--- ## Adding this line will cause compile error. ##
};
int main() {
B b;
B b2 = std::move(b); //## error at this line if the above line is added
return 0;
}
实时代码:https ://ideone.com/UTR9ob
错误是 invalid initialization of non-const reference of type 'B&' from an rvalue of type 'std::remove_reference<B&>::type {aka B}'
。
问题:
- (1) 哪些 C++ 语法规则强制执行该规则?换句话说,错误是什么意思?
- (2) 如果我想添加几乎什么都不做的析构函数(例如只打印调试日志)
B
,我真的必须遵循五规则吗?如果没有,如何编译?在我看来,仅仅因为这个而遵循五法则太乏味和肮脏。
我认为零规则只是一个好习惯。
但是,从这个例子来看,在我看来这是一个硬性规则,如果违反,我会得到编译错误。