MFC如何实现new出来的非模态窗口关闭时自动释放资源

众所周知,new出来的CDialog窗体在堆中开辟空间,不手动进行释放会造成内存泄露

Modal dialog boxes are normally created on the stack frame and destroyed when the function that created them ends. The dialog object’s destructor is called when the object goes out of scope.
Modeless dialog boxes are normally created and owned by a parent view or frame window — the application’s main frame window or a document frame window. The default OnClose handler calls DestroyWindow, which destroys the dialog-box window. If the dialog box stands alone, with no pointers to it or other special ownership semantics, you should override PostNcDestroy to destroy the C++ dialog object. You should also override OnCancel and call DestroyWindow from within it. If not, Don’t call the base class CDialog::OnCancel, because it calls EndDialog, which will make the dialog box invisible but will not destroy it.
You should override PostNcDestroy for modeless dialog boxes in order to delete this, since modeless dialog boxes are usually allocated with new. Modal dialog boxes are usually constructed on the frame and do not need PostNcDestroy cleanup.

1、非模态对话框是在堆中产生,必须要释放;模态对话框在栈中,过了作用域会自动释放
2、此时用IDOK,IDCANCEL关闭窗体时,应对OnOK,OnCancel重写,CDialog::OnOK();CDialog::OnCancel();应被替换为CDialog::DestroyWindow()。因为前者是会调用CDialog::EndDialog, 其是为模态对话框而设计,非模态调用它只能隐藏窗体而不会释放。
3、如果对话框为游离状态(指父窗体或其他窗体没有掌控指向该对话框的指针),就需要重载PostNcDestroy, 当然父窗体有该模态对话框的指针CDlg* pDlg,在适当的时候delete pDlg即可
总之:先DestroyWindow, 然后delete
用PostNCDestory将windows内核对象销毁,调用delete把对话框的c++对象销毁。
对于一个mfc的对话框对象,它实际上分为两部分,一部分是系统内核对象,用句柄标识,一部分是用于包装这个句柄的c++对象


我尝试对窗体类覆写以下函数

void myDlg::PostNcDestroy()
{
	// TODO: 在此添加专用代码和/或调用基类
	CDialog::PostNcDestroy();
	delete this;
}
void myDlg::OnCancel()
{
	// TODO: 在此添加专用代码和/或调用基类
	CDialog::OnCancel();
	DestroyWindow();
}

或者直接

void myDlg::OnCancel()
{
	// TODO: 在此添加专用代码和/或调用基类
	CDialog::OnCancel();
	DestroyWindow();
	delete this;
}

参考
非模态对话框的释放

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百口可乐__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值