对于虚拟析构函数,我是否需要为每个子类显式声明一个虚拟析构函数?
我有一个场景,我正在编写一些深入的面向对象的代码,具有多层抽象基类,我想知道是否必须为每个层显式声明一个析构函数。
编译器会生成一个已经是虚拟的默认编译器吗?还是我必须告诉它?
I've got a scenario where I'm writing somewhat deep object oriented code, with multiple layers of abstract base classes, and I'm wondering if I have to explicitly declare a destructor for each one.
Will the compiler generate a default one that's already virtual, or will I have to tell it to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
答案是否定的。这里唯一相关的要求是,具有 vtable 的类(即,至少具有一个虚函数)必须在其继承链中的某处至少有一个虚拟析构函数。通常,这意味着您的基本基类将提供一个空的虚拟析构函数。
The answer is no. The only relevant requirement here is that classes with a vtable (i.e., with at least one virtual function) must have at least one a virtual destructor somewhere in their inheritance chain. Typically this means that your fundamental base class will provide an empty virtual destructor.
一般来说,如果某个函数在基类中声明为虚函数,则无需在子类中显式声明它为虚函数。然而,这是一个很好的做法。
将子类中的析构函数显式声明为 virtual 不会给您带来任何重大优势,因此,如果您不想再编写一个 virtual 析构函数,请不要这样做。
In general if some function is declared virtual in base class, there is no need to explicitly declare it virtual in subclasses. However it is good practice.
Declaring destructors in subclasses as virtual explicitly doesn't give you any serious advantages, so if you don't wont to write one more virtual, don't do that.
默认析构函数不是虚拟的。如果将基类的析构函数声明为虚拟,则子类的析构函数将被覆盖,因此即使没有显式声明它们也是虚拟的。
如果您有一个类层次结构并且您的基类没有将析构函数声明为虚拟的,那么 GNU GCC 编译器甚至会发出警告,因为您很可能希望它是虚拟的。
The default destructor is not virtual. If you declare the destructor of your base class as virtual, the destructors of the subclasses will be overrides, and thus also be virtual even without explicitly declaring them to be.
The GNU GCC compiler even gives a warning if you have a class hierarchy and your base class does not declare the destructor to be virtual because you most likely want it to be.