析构函数的顺序

The order of destructor

本文关键字:顺序 析构函数      更新时间:2023-10-16
#include <iostream>
#include <cstring>
using namespace std;
class Ghost{
public:
    Ghost(){
        strcpy(name, "");
        cout << "Ghost(" << name <<")" <<endl;
    }
    Ghost(char n[]){
        strcpy(name, n);
        cout << "Ghost(" << name << ")" << endl;
    }
    ~Ghost(){
        cout <<"~Ghost(" << name << ")" << endl;
    }
private:
    char name[20];
};
class PacMan{
public:
    PacMan(){
        inky = new Ghost("Inky");
        pinky = NULL;
        cout << "PacMan()" << endl;
    }
    PacMan(Ghost* other){
        inky = NULL;
        pinky = other;
        cout << "PacMan(other)" << endl;
    }
    ~PacMan(){
        if (inky!= NULL)
            delete inky;
        cout <<"~PacMan()" << endl;
    }
private:
    Ghost blinky;
    Ghost *inky;
    Ghost *pinky;
};
int main(){
    PacMan pm1;
    Ghost* other = new Ghost("other");
    PacMan* pm2 = new PacMan(other);
    delete pm2;
    delete other;
    return 0;
}

对于此程序,它输出:

Ghost()
Ghost(Inky)
PacMan()
Ghost(other)
Ghost()
PacMan(other)
~PacMan()
~Ghost()
~Ghost(other)
~Ghost(Inky)
~PacMan()
~Ghost()

我想知道第一个输出 Ghost(( 来自哪里,以及为什么最后三个输出不是

~PacMan()
~Ghost(Inky)
~Ghost()

我认为析构函数的顺序与构造函数顺序相反,是真的吗?

第一个幽灵是PacMan成员blinky

关于最后一个命令:摧毁pm1执行者

~PacMan(){
        if (inky!= NULL)
            delete inky;
        cout <<"~PacMan()" << endl;
    }  

然后blinky也被删除。
如果你想要相反的顺序,你必须写在这里。