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
析构函数
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构造函数
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析构函数