c++ - c++ explicitly call the destructor

 

Destructor server primarily to relinquish resources acquired either within the constructor or during the lifetime. the lifetime of the class object, again such as freeing a mutal exclsion lock or deleting memory allocated through operator new.

 

 

 

destructor is implicitly called when the object is out of scope, such as the local object goes out of scope, or when program exit, the global object destructors are called. or explicitly when you call the delete operator. 

 

given the following code. 

 

void destructor_life_cycle_test()
{
	Account local("Anna live Plurablle", 1000);
	Account &loc_ref = global;
	auto_ptr<Account> pact(new Account("stephen Dedalus"));

	{
		Account local_too("Stephen Hero");
		// the local_too will destroy before exit the current local space. 
	}
	// the auto_ptr will destruct here

}

 

can you see which destructor is called at different stage?

 

 

So, why do we need to call explicitly the destructor, given the following code, 

 

given the following example. 

 

 

	char *arena = new char[sizeof Image];

	Image * ptr = new (arena) Image("Quasimodo");

	Image *ptr = new (arena) Image("Esmerelda");

	//you cannot delete the ptr, because it will reclaim the memory in addition to call the destructor
	delete ptr;

	// but instead, you should do something like this:
	ptr->~Image();

	// and when  you finish using the arena memory , you can free the location by this 
	delete arena;
	// it will not call the destructor, because arena is of type char *

 

it is obvious that we might need explictly call the destructor when we are manually managing the memory and allocation, we need to call the destructor to explicitly manage the life cycle of the object ourselves.

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值