什么时候使用虚拟析构函数? [英] When to use virtual destructors?
问题描述
我对大多数OO理论有一个坚定的理解,但是让我很困惑的一件事是虚拟析构函数。
I have a solid understanding of most OO theory but the one thing that confuses me a lot is virtual destructors.
我认为析构函数总是被调用
I thought that the destructor always gets called no matter what and for every object in the chain.
推荐答案
当您可以通过指向基类的指针删除派生类的实例时,虚拟析构函数非常有用:
Virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class:
class Base
{
// some virtual methods
};
class Derived : public Base
{
~Derived()
{
// Do some important cleanup
}
}
在这里,你会注意到我没有声明Base的析构函数 virtual
。现在,让我们看看下面的代码片段:
Here, you'll notice that I didn't declare Base's destructor to be virtual
. Now, let's have a look at the following snippet:
Base *b = new Derived();
// use b
delete b; // Here's the problem!
由于Base的析构函数不是 virtual
code> b 是指向 Derived
对象的 Base *
code> delete b 有未定义的行为。在大多数实现中,对析构函数的调用将像任何非虚拟代码一样被解析,这意味着基类的析构函数将被调用而不是被派生类的析构函数,从而导致资源泄露。
Since Base's destructor is not virtual
and b
is a Base*
pointing to a Derived
object, delete b
has undefined behaviour. In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.
总而言之,当它们要被多态操作时,总是使基类的析构函数 virtual
。
To sum up, always make base classes' destructors virtual
when they're meant to be manipulated polymorphically.
如果你想防止通过基类指针删除一个实例,你可以使基类析构器受保护和非虚拟;通过这样做,编译器不会让你在基类指针上调用 delete
。
If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call delete
on a base class pointer.
更多关于 Herb Sutter的这篇文章中的虚拟化和虚拟基类析构函数。
You can learn more about virtuality and virtual base class destructor in this article from Herb Sutter.
这篇关于什么时候使用虚拟析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!