问题
MFC程序中,在主程序类的InitInstance中创建由CWnd派生的CMyWnd窗口对象,程序关闭时,在vs的输出窗口报告有内存泄漏。
分析
单文档、多文档程序都是在InitInstance中new出主窗口,我也是仿照那个写的。但存在区别,CMyWnd类是从CWnd类派生,而前者是派生自CFrameWnd。
那原因就从CFrameWnd身上找吧,方法:在自动生成的单文档程序的主窗口类的析构函数中下个断点,关闭程序,从函数调用堆栈中即可看出是哪里删除这个主窗口对象的,查找到以下函数:
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;
}
MSDN对PostNcDestroy的说明也证实了这一点:
Called by the default OnNcDestroy member function after the window has been destroyed. Derived classes can use this function for custom cleanup such as the deletion of the this pointer.
解决方案:
首先看下OnNcDestroy的文档说明:
Override PostNcDestroy if you want to perform your own cleanup, such as a delete this operation. If you override OnNcDestroy, you must call OnNcDestroy in your base class to ensure that any memory internally allocated for the window is freed.
这里给出的解决办法,重载虚函数PostNcDestroy去删除本身