c++ - 添加新成员复制c-for/copy of-tor/序列化提醒

标签 c++

几乎所有的 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/

相关文章:

c++ - 如何在C++程序中设置自定义断点?

c++ - 为什么此代码在具有多字节字符集但不具有 unicode 字符集的 visual studio 中完美运行?

c++ - 错误 : ISO C++ forbids in-class initialization of non-const static member

c++ - 在新建和删除操作中花费了意外的时间

c++ - 关于 C++ 中构造函数的奇怪行为

c++ - 指向设备常量的 CUDA 指针

c++ - 在 C++20 中使用 auto 转发参数?

c++ - 为什么 C++Builder 无法创建预编译头文件?

c++ - 两次设置 QApplication::style 后程序崩溃

c++ - 如何通过多线程避免 C++ 中的挂起处理