new与delete必须成对使用吗?

10 篇文章 0 订阅

对于本文标题的问题,相信许多人会跟两个星期前的我一样,会说YES。
请看下面我的经历——


两周前,程序关闭时莫名出错。

找了许久发现是ExitInstance时delete一个指针出错,它指向CFrameWnd的子类,
而且此时这个指针值为0xdddddddd,这个注定不寻常的地址含义是:Deleted。


为什么它已经被删除了?答案在MSDN中——

Do not use the C++ delete operator to destroy a frame window. UseCWnd::DestroyWindow instead. TheCFrameWnd implementation ofPostNcDestroy will delete the C++ object when the window is destroyed. When the user closes the frame window, the defaultOnClose handler will callDestroyWindow.


原来关闭窗体会导致DestroyWindow被调用,而最终会导致PostNcDestroy 被调用。
下面MFC函数实现在C:\Program Files\Microsoft Visual Studio 9.0\VC\atlmfc\src\mfc\winfrm.cpp 文件中。

void CFrameWnd::PostNcDestroy()
{
	// default for frame windows is to allocate them on the heap
	//  the default post-cleanup is to 'delete this'.
	// never explicitly call 'delete' on a CFrameWnd, use DestroyWindow instead
	delete this;
}


红色部分,已经说的相当明确了,无需再继续解释了吧。所以,标题的答案是——
【标准C++中也许这句话成立;但是MFC“主动”替我们做了许多事后,再单纯看我们自己的代码,就不一定哦。】


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值