添加新成员以复制c-tor/copy o-tor /序列化提醒

bay*_*yda 9 c++

几乎所有的c ++项目都有复制c-tor /复制操作符/序列化方法等的类.这通常与所有成员一起做.

但有时开发人员会忘记为此功能添加新成员.
你知道任何简单的,而不是wrapp所有成员的方式会提醒开发人员做某事或在这个函数中写noop(memeber_name_).

我试图发明一些但却有错.

PS:单元测试可以防止这个问题,但我想要一些编译时间.

小智 1

template<class T>
class SafeMember {
public:
    T _;    /* short name for convenience */
    SafeMember(T const& obj) : _(obj) { }
};
Run Code Online (Sandbox Code Playgroud)

像这样使用:

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;
};
Run Code Online (Sandbox Code Playgroud)

现在,当您添加“ SafeMember<int> age”成员并忘记更新复制构造函数时,编译将失败。

对于“无操作”提示,开发人员将添加一个像“:age(0)”这样的初始值设定项。

注意:这并不能保护您的operator=()或serialize()函数免受位腐烂,只能保护构造函数。不过,希望这应该足够了:一旦您看到构造函数中的遗漏,您可能会记得也检查其他函数。