析构函数会在这个对象的生命周期结束之前被调用,用来回收这个对象所使用的资源,可以做一些收尾清理工作。
定义:
virtual ~B15(){
cout << "destructor called" << endl;
}
以下代码new了一个A15对象,然后调用其方法say()之后马上释放,然后当前进程sleep3秒之后程序结束运行。
#include <iostream>
#include <unistd.h>
using namespace std;
class B15{
public:
B15() {
cout << "default constructor A15" << endl;
}
int say() {
cout << "A say" << endl;
return 0;
}
virtual ~B15(){
cout << "destructor called" << endl;
}
};
int main() {
B15 *b = new B15();
b->say();
delete b;
cout << "start sleep" << endl;
sleep(2);
cout << "end" << endl;
return 0;
}
运行之后打印如下:
default constructor A15
A say
destructor called
start sleep
可以看出析构函数执行在sleep之前。
可以把以上代码修改为:
#include <iostream>
#include <unistd.h>
using namespace std;
class B15 {
public:
B15() {
cout << "default constructor A15" << endl;
}
int say() {
cout << "A say" << endl;
return 0;
}
virtual ~B15(){
cout << "destructor called" << endl;
}
};
int main() {
B15 *b = new B15();
b->say();
cout << "start sleep" << endl;
sleep(2);
cout << "after sleep" << endl;
delete b;
cout << "end" << endl;
return 0;
}
也就是先sleep,然后再释放对象b,打印日志如下:
default constructor A15
A say
start sleep
after sleep
destructor called
end
对比2个程序可以证明,是在delete b的时候调用了析构函数.