虚拟析构函数是否继承? [英] Are virtual destructors inherited?

查看:437
本文介绍了虚拟析构函数是否继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个基类和一个虚拟析构函数。还有一个派生类也声明一个虚拟析构函数?

If I have a base class with a virtual destructor. Has a derived class to declare a virtual destructor too?

class base {
public:
    virtual ~base () {}
};

class derived : base {
public:
    virtual ~derived () {} // 1)
    ~derived () {}  // 2)
};

具体问题:


  1. 是1)和2)相同吗?

  2. 如果没有任何动作,可以省略派生的析构函数吗?

  3. 声明派生析构函数的最佳做法是什么?如果可能,声明为虚拟,非虚拟或忽略它?


推荐答案


  1. 是的,他们是一样的。派生类不声明虚拟的东西并不会阻止虚拟。事实上,没有办法阻止任何方法(包含析构函数)在派生类中是虚拟的,如果它是基类中的虚拟方法。

  2. 是的,派生类中的析构函数如果没有什么可以省略类。无论它的虚拟。

  3. 如果可能,我会省略它。为了清楚起见,我总是对派生类中的虚函数再次使用 virtual 关键字。

  1. Yes, they are the same. The derived class not declaring something virtual does not stop it from being virtual. There is, in fact, no way to stop any method (destructor included) from being virtual in a derived class if it was virtual in a base class.
  2. Yes, a destructor in a derived class can be omitted if it has nothing to do. And it doesn't matter whether or not its virtual.
  3. I would omit it if possible. And I always use the virtual keyword again for virtual functions in derived classes for reasons of clarity. People shouldn't have to go all the way up the inheritance hierarchy to figure out that a function is virtual.

作为一个小点,人们不应该继承继承层次结构以确定一个函数是虚拟的。对于项目3.在注释中已经指出,如果析构函数未声明,编译器生成一个默认的(仍然是虚拟的)。

As a small point for item 3. It has been pointed out in comments that if a destructor is undeclared the compiler generates a default one (that is still virtual). And that default one is an inline function.

内联函数可能会将更多的程序暴露给程序的其他部分,使共享库的二进制兼容性变得棘手。此外,增加的耦合可导致面对某些种类的大量重新编译。例如,如果你决定你真的想要一个虚拟析构函数的实现,那么调用它的每一段代码都需要重新编译。如果你已经在类体中声明了它,然后在 .cpp 文件中将其定义为空,那么无需重新编译就可以很好地修改它。

Inline functions potentially expose more of your program to changes in other parts of your program and make binary compatibility for shared libraries tricky. Also, the increased coupling can result in a lot of recompilation in the face of certain kinds of changs. For example, if you decide you really do want an implementation for your virtual destructor then every piece of code that called it will need to be recompiled. Whereas if you had declared it in the class body and then defined it empty in a .cpp file you would be fine changing it without recompiling.

我的个人选择仍然是在可能的时候省略它。在我看来,它杂乱的代码,编译器有时可以做一些更高效的事情与一个空的默认实现。但是,你可能会有一些限制,这是一个不好的选择。

My personal choice would still be to omit it when possible. In my opinion it clutters up the code, and the compiler can sometimes do slightly more efficient things with a default implementation over an empty one. But there are constraints you may be under that make that a poor choice.

这篇关于虚拟析构函数是否继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆