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)

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