对于本文标题的问题,相信许多人会跟两个星期前的我一样,会说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“主动”替我们做了许多事后,再单纯看我们自己的代码,就不一定哦。】