C++析构函数的调用与内存的释放先后顺序
程序员文章站
2024-03-26 11:15:53
...
结论:首先调用析构函数,然后释放成员变量的内存。
#include <iostream>
#include <string>
using namespace std;
int num = 0;
class Student{
public:
~Student(){
cout << num++ << endl;
cout << "~Student() is invoked!" << endl;
}
private:
string name;
int age;
};
class School{
public:
School()
:ps(new Student())
{
}
~School(){
delete ps;
cout << "~School() is invoked!" << endl;
}
private:
Student s; // 定义在前面,却是在delete ps之后释放的内存
Student* ps;// 定义在后面,却是在释放s内存之前释放堆中的内存
int number;
};
int main()
{
School school;
return 0;
}
// 程序输出结果
0
~Student() is invoked!
~School() is invoked!
1
~Student() is invoked!