仅重新初始化派生类中的所有成员变量

时间:2016-10-08 13:39:55

标签: c++ class initialization

我有两个班级:

class NonCopyable {
private:
    int key;
protected:
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable& operator = (const NonCopyable &) = delete;
};

class Derived : public NonCopyable {
private:
    std::vector<int> numbers;
    float f;
    int* ptr;
public:
    Derived() : f(5.0f), ptr(nullptr) {}
    ~Derived();
};

现在,我想重新初始化 Derived 类中的所有值,并调用相应的析构函数。也就是说,不应该触及 NonCopyable 类,但应该更改 Derived 类,就好像它是新初始化的一样。

实现这一目标的最简单方法是什么?我试图避免创建一个手动重新初始化每个成员变量的成员函数。

显然,我不能使用以下方法:

Derived d;
// [...] many changes to d
d = Derived();

因为复制构造函数是从 NonCopyable 类中删除的,而且它会改变 NonCopyable 的成员变量这一事实并非如此。

1 个答案:

答案 0 :(得分:4)

如果将私人数据移动到单独的聚合中,则会变得更加容易:

struct DerivedData {
    std::vector<int> numbers;
    float f = 5.0;
    int* ptr = nullptr;
};

class Derived : public NonCopyable {
    DerivedData data;
public:
    ~Derived();
    void reset() { data = DerivedData(); }
};