【问题标题】:The order of destructor析构函数的顺序
【发布时间】:2017-10-20 13:35:01
【问题描述】:
#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()

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

【问题讨论】:

  • 调试器是解决此类问题的正确工具。 询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 edit 您的问题包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
  • delete nullptr; 是合法的。 if ( p != nullptr ) delete p; 是一种反模式。

标签: c++ class destructor


【解决方案1】:

第一个 Ghost 是 PacMan 成员 blinky

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

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

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

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 1970-01-01
    • 2018-05-07
    • 2015-08-02
    • 2013-06-24
    • 2016-03-18
    • 2018-05-08
    相关资源
    最近更新 更多