几乎所有的 c++ 项目都有带有复制 c-tor/复制运算符/序列化方法等的类。通常对所有成员做一些事情。
但有时开发人员会忘记向该函数添加新成员。
你知道任何简单的,不包装所有成员的方式,它会提醒开发人员做一些事情或在这个函数中写 noop(memeber_name_)。
我试图发明一些东西,但失败了。
PS:单元测试可以防止这个问题,但我想要一些编译时间。
最佳答案
template<class T>
class SafeMember {
public:
T _; /* short name for convenience */
SafeMember(T const& obj) : _(obj) { }
};
这样使用:
class Student {
public:
Student(string surname, Color hairColor)
: surname(surname)
, hairColor(hairColor) { }
Student(Student const& other)
: surname(other.surname)
, hairColor(other.hairColor) { }
Student& operator=(Student const& other) {
surname = other.surname;
hairColor = other.hairColor;
return *this;
}
string getSurname() const { return surname._; }
// The foo._ syntax is better than implicit conversion because
// it lets us call member functions, like substr in this example:
bool isSlavic() const {return surname._.substr(surname._.size()-2)=="ev";}
void dyeHair(Color newColor) { hairColor = newColor; }
private:
SafeMember<string> surname;
SafeMember<Color> hairColor;
};
现在,当您添加一个“SafeMember<int> age
”成员而忘记更新您的复制构造函数时,编译将会失败。
对于“无操作”提示,开发人员会添加一个初始化程序,如“:age(0)”。
注意:这并不能保护您的 operator=() 或 serialize() 函数免受位腐烂,只能保护构造函数。不过,希望这应该足够了:一旦您看到构造函数中的遗漏,您可能会记得也检查其他函数。
关于c++ - 添加新成员复制c-for/copy of-tor/序列化提醒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/655856/