1. 什么是析构函数
1.1 语法

- ~在C中是按位取反的操作。
- 析构函数是对象销毁时,自动被调用的,完成对象动态资源的清理操作。
- 这里的动态资源指的是,只是通过对象里面的成员所维护的,不是对象本身的资源。需要手动销毁清理的。
- 不能被重载,所以一个类只有一个析构函数。
2. 析构函数的应用

- 第二句中离开作用域的意思应该就是,离开了对象定义时所在的{ }。而不是对象所在函数结束时(即 return时)。
#include <iostream>
#include <unistd.h>
using namespace std;
class Integer{
public:
Integer(int pi){
// 这下就有了对象维护的动态资源
m_pi = new int(pi);
}
// 对象被销毁时,析构函数自动执行
~Integer(void){
cout << "析构函数" << endl;
delete(m_pi);
}
void print(void){
cout << *m_pi << endl;
}
private:
int* m_pi;
};
int main(void){
if(1){
// 栈区对象
Integer i(100);
i.print();
// 堆区对象
Integer* j = new Integer(200);
delete j; // 执行析构函数释放堆区对象的动态资源
cout << "test_0" << endl;
} // 执行析构函数释放栈区对象的动态资源
cout << "test_1" << endl;
return 0;
}
$ ./a.out
100
析构函数 # delete j;
test_0
析构函数 # }
test_1
3. 缺省析构函数

#include <iostream>
#include <unistd.h>
using namespace std;
class A{
public:
A(void){
cout << "A构造函数" << endl;
}
~A(void){
cout << "A析构函数" << endl;
}
};
class B{
// 编译器会自动提供一个缺省构造函数, 和一个缺省析构,和一个缺省拷贝
public:
A m_a; //成员子对象
};
int main(void){
B b;
return 0;
}
$ ./a.out
A构造函数
# 执行到}, 会自动去调用b的缺省析构函数,b的成员子对象会自动调用相应的析构函数
A析构函数
4. 对象的创建和销毁的过程

- 先分配内存,再构造
- 先析构,再释放内存
#include <iostream>
#include <unistd.h>
using namespace std;
class A{
public:
A(void){
cout << "A构造函数" << endl;
}
~A(void){
cout << "A析构函数" << endl;
}
};
class B{
public:
B(void){
cout << "B构造函数" << endl;
}
~B(void){
cout << "B析构函数" << endl;
}
A m_a; //成员子对象
};
int main(void){
B b; // 先在栈区分配一块内存,然后再执行构造函数
return 0;
}
$ ./a.out
// 创建对象时,先调用成员子对象的构造函数(按声明顺序),再去调用对象的构造函数
A构造函数
B构造函数
// 销毁对象时,先调用对象的析构函数(按声明逆顺),再去调用成员子对象的析构函数
B析构函数
A析构函数
版权声明:本文为guaiderzhu1314原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。