考虑一个简单的界面/实现设计:
class Base
{
public:
virtual ~Base()
{
// Virtual empty destructor
}
};
class Derived : public Base
{
public:
virtual ~Derived()
{
// Lots of clean up code here
// ...
}
};
通过这种设计,我了解到以下代码是安全有效的:
Base* base = new Derived();
delete base; // Both Base::~Base and Derived::~Derived get called
但是,想象一下如果有一个新类:
class DerivedEx : public Derived
{
public:
// No destructor here, relying on default destructor generated by compiler
};
DerivedEx “安全”吗?
为了安全起见,我一直认为我必须在DerivedEx中实现一个虚拟的空析构函数。但我想知道这是否是多余和不必要的,是否有任何我不知道的“陷阱”。