CFrameWnd创建要在堆上

问题描述

最近写一个程序,在主界面中弹出一个窗口,就想当然的想从CFrameWnd下继承一个新类,然后将此类的对象作为一个成员变量放在主界面窗口类中。这个从CFrameWnd继承来的窗口可以正常显示,但是一旦关闭此窗口,就报以下错误了:
在这里插入图片描述

问题分析

MSDN明确指出了,CFrameWnd要创建在堆上:

Before you call either Create or LoadFrame, you must construct the frame-window object on the heap using the C++ new operator. Before calling Create, you can also register a window class with the AfxRegisterWndClass global function to set the icon and class styles for the frame.

查看MFC源码可知,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;
}

结论

如果需要使用一些工具栏,状态栏之类的,可以从CFrameWnd派生下来,可参见本人另一篇文章CWnd直接派生的窗口下使用CToolBar笔记

像前述需求的话,推荐使用非模态对话框,或者从CWnd下派生就行了(注:CWnd::Create只能创建子窗口,要创建非子窗口要调用CWnd::CreateEx)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章