我有两节课:
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的成员变量。
如果将私有数据移动到单独的聚合中,将变得更加容易:
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(); }
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句