本文介绍了这是MFC中的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// CMyDialog inherits from CDialog
void CMyFrame::OnBnClickedCreate()
{
    CMyDialog* dlg = new CMyDialog();
    dlg->Create( IDD_MYDIALOG, m_thisFrame );
    dlg->ShowWindow( SW_SHOW );
}

我很确定这个漏洞。我真正要求的是:在MFC有任何魔术,当对话框被销毁时,对话框清理。如果dlg不是指针而是在堆栈上声明,那么它将如何工作 - 当dlg超出范围时,析构函数不会销毁窗口。

I'm pretty sure this leaks. What I'm really asking is: is there any "magic" in MFC that does dialog cleanup when the dialog is destroyed. How would it work if dlg wasn't a pointer but declared on the stack - wouldn't the destructor destroy the window when dlg goes out of scope.

推荐答案

是的,它是内存泄漏在你的情况下,但你可以避免内存泄漏的情况下,无模式对话框分配在堆上通过使用重写 PostNcDestroy

Yes, it is memory leak in your case but you can avoid memory leak in cases where modeless dialog allocated on the heap by making use of overriding PostNcDestroy.

对话框不是为自动清理而设计的(主窗口,视窗是)。
如果你想为对话框提供自动清理,那么你必须覆盖你的派生类中的 PostNcDestroy 成员函数。要向类中添加自动清理,请调用您的基类,然后执行删除此。要从您的类中删除自动清理,请直接调用 CWnd :: PostNcDestroy ,而不是直接基础中的 PostNcDestroy 类。

Dialogs are not designed for auto-cleanup ( where as Main frame windows, View windows are).In case you want to provide the auto-cleanup for dialogs then you must override the PostNcDestroy member function in your derived class. To add auto-cleanup to your class, call your base class and then do a delete this. To remove auto-cleanup from your class, call CWnd::PostNcDestroy directly instead of the PostNcDestroy member in your direct base class.

void MyDialog::PostNcDestroy()
{

    CDialog::PostNcDestroy();
    delete this;
}

这是如何工作的(来自MSDN):

How this works (from MSDN):

delete this将释放任何C ++
C ++对象。
即使默认的CWnd
析构函数调用DestroyWindow如果
m_hWnd是非NULL的,这不会导致
到无限递归,因为句柄
将被分离并且NULL在
清理阶段。

"delete this" will free any C++ memory associated with the C++ object. Even though the default CWnd destructor calls DestroyWindow if m_hWnd is non-NULL, this does not lead to infinite recursion since the handle will be detached and NULL during the cleanup phase.

您也可以参考MSDN()。

You can also refer MSDN (Destroying Window Objects ) for further details.

注意:

这适用于可在上分配的无模式对话框。

This works for modeless dialog that can be allocated on the heap.

这篇关于这是MFC中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:41
查看更多