C ++中的虚拟默认析构函数 [英] Virtual Default Destructors in C++
问题描述
我有一大堆继承自基类(准则)的继承类(准则).这是criterion
的代码
I've got a large set of inherited classes (criteria) which inherit from a base class (criterion). Here's criterion
's code
class criterion
{
public:
virtual unsigned __int32 getPriorityClass() const = 0;
virtual BOOL include(fileData &file) const = 0;
virtual void reorderTree() = 0;
virtual unsigned int directoryCheck(const std::wstring& directory) const = 0;
virtual std::wstring debugTree() const = 0;
};
从这一类派生的类的一些示例:
Some examples of derived classes from this one:
class fastFilter : public criterion
{
public:
void reorderTree() {};
unsigned int directoryCheck(const std::wstring& /*directory*/) const { return DIRECTORY_DONTCARE; };
unsigned __int32 getPriorityClass() const { return PRIORITY_FAST_FILTER; };
};
class isArchive : public fastFilter
{
public:
BOOL include(fileData &file) const
{
return file.getArchive();
}
std::wstring debugTree() const
{
return std::wstring(L"+ ISARCHIVE\n");
};
};
由于我这里根本没有析构函数,但这应该是基类,因此我需要插入一个空的虚拟析构函数,即这样吗?:
Since I don't have a destructor here at all, but yet this is supposed to be a base class, do I need to insert an empty virtual destructor, I.e. like this?:
virtual void ~criterion() = 0;
如果需要该虚拟析构函数声明,那么所有中间类也都需要一个吗? IE.上面的fastFilter也需要虚拟析构函数吗?
If that virtual destructor declaration is needed, do all intermediate classes need one as well? I.e. would fastFilter above need a virtual destructor as well?
推荐答案
是的-基类需要一个虚拟析构函数,即使它为空.如果不这样做,那么当delete
通过基础指针/引用成为派生对象时,派生对象的成员对象将没有机会正确地销毁自己.
Yes - the base class needs a virtual destructor, even if it's empty. If that is not done, then when something delete
's a derived object through a base pointer/reference, the derived object's member objects will not get a chance to destroy themselves properly.
派生类无需声明或定义自己的析构函数,除非它们需要除默认析构函数行为以外的其他东西.
Derived classes do not need to declare or define their own destructor unless they need something other than default destructor behavior.
这篇关于C ++中的虚拟默认析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!