使用虚拟的破坏顺序 [英] order of destruction using virtual

查看:137
本文介绍了使用虚拟的破坏顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些人请帮助什么是销毁的顺序是当我使用虚拟函数。它从基类开始,然后是派生类?

Can some one please help what the order of destruction is when I am using virtual functions. Does it start with base class and then derived class ?

推荐答案

因为我没有看到虚函数如何改变任何对象的破坏顺序,我假设你是指在虚拟 继承 情况下基类和数据成员的销毁顺序。

Since I don't see how virtual function change any objects' destruction order, I assume you're referring to the order of destruction for base classes and data members in a virtual inheritance scenario.

子对象

Sub-objects are constructed


  1. 基类是从大多数基础到大多数派生构建的;

  2. strong>以它们的声明的基础类的顺序构造;

  3. 虚拟基类 ,其中自身遵守上述两条规则;

  4. 数据成员是在包围对象的构造函数主体执行之前构建的。

  1. base classes are constructed from most base to most derived;
  2. multiple base classes are constructed in the order of their declaration as base classes;
  3. virtual base classes are constructed before all others, amongst themselves adhering to the above two rules;
  4. data members are constructed before the enclosing object's constructor's body is executed, in order of their declaration.

毁坏 结构完全相反,记住上述。

Destruction is simply the opposite of construction, so you only need to memorize the above.

然而,上述四个规则是按顺序的,因为这是有道理的,如果你明白为什么这个顺序有意义,你甚至不必记住这四个规则,但可以从你的理解(正如我所做的)推断。因此,让我们检查一下顺序:

However, the above four rules are in that order because that makes sense, and if you understand why this order makes sense, you will not even have to memorize those four rules, but can infer them from your understanding (as I just did). So let's examine that order:


  • 你可能想使用基类从派生类的构造函数提供的任何服务。当然,你不能在实际构造之前使用(基础)类对象。因此,当构造一个派生类时,基类需要被构造。 (顺便说一下,这也解释了为什么虚函数调度在构造函数中不能完全工作:当子对象被构造时,只有基类的子对象已经被构造;派生类的子对象还没有

  • 由于多个基类是相同的兄弟节点,所以一些函数不能被调用到派生类。顺序必须任意挑选。最后,声明的顺序是最简单的使用。数据成员(也是同等的兄弟),遵循相同的(或多或少任意的)声明顺序规则。

  • 虚拟基类是奇怪的野兽。因为总是只有一个虚拟基类的一个子对象,有一个特殊的规则,它总是需要首先构造,从最衍生的类的构造函数。 (这就是为什么虚拟基类最适合作为没有数据和默认构造函数的抽象基类的原因。)

这篇关于使用虚拟的破坏顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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