析构函数的顺序
The order of destructor
#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
也被删除。
如果你想要相反的顺序,你必须写在这里。
相关文章:
- 优先顺序:智能指针和类析构函数
- C++成员的析构函数顺序与shared_ptr
- C++:使用方法调用析构函数的顺序是什么?
- 有没有办法保证析构函数的相对顺序?
- std::unique_ptr析构函数顺序
- C++销毁顺序:在类析构函数之前调用字段析构函数
- 构造函数和析构函数的顺序
- 析构函数的顺序
- 析构函数的奇怪调用顺序
- 共享指针析构函数中的内存顺序
- C++-销毁顺序-函数的静态成员在主类析构函数之前被销毁
- 更改析构函数顺序
- 在C++中为临时库调用析构函数的顺序是什么
- 构造函数和析构函数调用的顺序
- 析构函数调用的顺序C++
- 没有调用C++析构函数,具体取决于链接顺序
- 在C++中,析构函数的调用顺序和成员变量的销毁顺序是什么
- 如何强制实施析构函数的调用顺序
- C++构造函数和析构函数顺序
- 使用继承时构造函数/析构函数调用的顺序