C++析构函数destructor入门

析构函数会在这个对象的生命周期结束之前被调用,用来回收这个对象所使用的资源,可以做一些收尾清理工作。

定义:

 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的时候调用了析构函数.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值