继承体系中 destructor 的执行次序

来源:互联网 发布:模特兼职知乎 编辑:程序博客网 时间:2024/05/01 00:46

《深度探索C++对象模型》P.233 L.-2: 

一个由程序员定义的 destructor 被扩展的方式类似 constructor 被扩展的方式,但顺序相反:

1. 如果 object 内带一个 vptr,那么首先重设 (reset) 相关的 virtual table;
    If the object contains a vptr, it is reset to the virtual table associated with the class.

2. destructor 的函数本身现在被执行,也就是说 vptr 会在程序员的码执行前被重设 (reset);
    The body of the destructor is then executed; that is, the vptr is reset prior to evaluating the user-supplied code.

3. 如果 class 拥有 member class objects,而后者拥有 destructors,那么它们会以其声明顺序的相反顺序被调用;
    If the class has member class objects with destructors, these are invoked in the reverse order of their declaration.

4. 如果有任何直接的(上一层)nonvirtual base classes 拥有 destructors,它们会以其声明顺序的相反顺序被调用;
    If there are any immediate nonvirtual base classes with destructors, these are invoked in the reverse order of their declaration.

5. 如果有任何 virtual base classes 拥有 destructor,而当前讨论的这个 class 是最尾端 (most-derived) 的 class,那么它们会以其原来的构造顺序的相反顺序被调用。
    If there are any virtual base classes with destructors and this class represents the most-derived class, these are invoked in the reverse order of their original construction.

侯捷认为正确的顺序应该是 2、3、1、4、5。即:

1. destructor 的函数本身首先被执行;

2. 如果 class 拥有 member class objects,而后者拥有 destructors,那么它们会以其声明顺序的相反顺序被调用;

3. 如果 object 内带一个 vptr,则现在被重新设定,指向适当之 base class 的 virtual table;

4. 如果有任何直接的(上一层)nonvirtual base classes 拥有 destructors,它们会以其声明顺序的相反顺序被调用;

5. 如果有任何 virtual base classes 拥有 destructor,而当前讨论的这个 class 是最尾端 (most-derived) 的 class,那么它们会以其原来的构造顺序的相反顺序被调用。

从下面测试代码的输出,可以看出,在 VC++ 2005 编译器中,侯捷的说法是正确的。

测试代码:

程序输出: