多重继承情况下的销毁顺序

Order of destruction in the case of multiple inheritance

在多重继承的情况下,销毁顺序是否明确?

struct A
{
   ~A(){std::cout << "A\n";}   
};

struct B
{
   ~B(){std::cout << "B\n";}   
};

struct AB : public B, public A
{
    ~AB(){std::cout<<"AB\n";}   
};

int main()
{
    AB ab;
}

对于我的编译器打印的给定代码:

AB
B
A

但是我使用了更复杂的结构(包括CWinApp),我得到了不同的结果。那么顺序是否明确?如果是这样,排序规则是什么?

C++11 标准明确说明了这一点 (S10.1),适用于多重继承

The order of derivation is not significant except as specified by the semantics of initialization by constructor (12.6.2), cleanup (12.4), and storage layout (9.2, 11.1).

但是你可以保证销毁顺序是构造的逆序

来自[class.dtor]:

Bases and members are destroyed in the reverse order of the completion of their constructor (see 12.6.2).

构造函数排序,来自[class.base.init]:

In a non-delegating constructor, initialization proceeds in the following order:
— First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized [ ... ]
— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

以你的例子为例:

struct AB : public B, public A

构建顺序是B然后A然后AB。所以销毁顺序是AB然后A然后B

来自friendly manual(稍微缩写#2):

  1. The class's destructor is called.
  2. Destructors for nonstatic members in reverse order of declaration.
  3. Destructors for nonvirtual base classes are called in the reverse order of declaration.
  4. Destructors for virtual base classes are called in the reverse order of declaration.

因此您的编译器会发出按 AB、B、A 顺序进行析构的代码。

[编辑 20150725:Barry 的反复评论最终让我注意到我将 "This is not" 打错为 "This is also"。当然,打完之后,我 打了 才看到它。嗯。于是,下面改了个字。]

这是不是来自isocpp.org的FAQ的订单。该条目指的是有关构造函数排序的相同问题,其中出现文本 "Note that the order B1 and then B2 (or B1a then B1b) is determined by the order that the base classes appear in the declaration of the class, not in the order that the initializer appears in the derived class’s initialization list.",突出显示声明顺序是相关顺序。