内部类析构函数在基类析构函数之后调用 [英] Inner class destructor is called after Base class destructor

查看:125
本文介绍了内部类析构函数在基类析构函数之后调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的基本问题。

i have a basic and simply question.

我有这种情况:

#include <iostream>
using namespace std;

class Inner1
{
public:
    ~Inner1() {cout << "Inner1 Des\n";};
};

class Inner2
{
public:
    ~Inner2() {cout << "Inner2 Des\n";};
};

class Base
{
public:
    ~Base() {cout << "Base Des\n";};

    Inner1 inner1;
    Inner2 inner2;
};

int main() {
    Base base;
    return 0;
}

我的控制台现在告诉我:

And my console tells me now this:


基本析构函数称为

Inner2析构函数称为

Inner1析构函数称为

Base destructor called
Inner2 destructor called
Inner1 destructor called

这是正常现象吗?因为某些功能的功能

已在我的基类析构函数中销毁,并且内部类依赖

Is this the normal behavior? Because the functionality for some functions
is already destroyed in my Base Class destructor and the Inner classes rely on them.

不推荐使用的解决方法:

只需在对象的第一个位置添加驱逐舰类:

Just add a "Destroyer" class with object at the first position:

[...]
class Base
    {
    public:
        ~Base() {cout << "Base Des\n";};

        class Destroyer
        {
             ~Destroyer()
             {
                 //Put the stuff here because this destr will be called last
                 cout << "Destroyer Des\n";
             }
        } _destroyer;
        Inner1 inner1;
[...]

感谢您的帮助

推荐答案


这是正常行为吗?

Is this the normal behavior?

是。子对象析构函数由容器类的析构函数调用。特别是,在执行了容器类析构函数的主体之后,子对象将被销毁。

Yes. Subobject destructors are called by the destructor of the container class. In particular, the subobjects will be destroyed after the body of the container classes destructor has been executed.


因为某些功能$ b的功能$ b已在我的基类析构函数中销毁,内部类依赖它们。

Because the functionality for some functions is already destroyed in my Base Class destructor and the Inner classes rely on them.

如果内部类[ sic]析构函数依赖于包含它们的 Base 实例。在那种情况下, Base 不应包含它们作为成员,否则它们的析构函数不应依赖于 Base

That's only a problem if the inner classes [sic] destructors rely on the Base instance that contains them. In that case either Base should not contain them as members, or their destructor should not depend on Base.

这篇关于内部类析构函数在基类析构函数之后调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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