gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:38:11 26 4
gpt4 key购买 nike

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

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),我得到了不同的结果。那么顺序是否明确?如果是这样,排序规则是什么?

最佳答案

来自 [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

关于c++ - 多重继承情况下的销毁顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31518581/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com