这是MFC中的内存泄漏 [英] Is this a memory leak in MFC

查看:580
本文介绍了这是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):


当销毁Windows窗口时,发送到
窗口的
最后一个Windows消息是WM_NCDESTROY。该消息的默认
CWnd处理程序
(CWnd :: OnNcDestroy)将从C ++对象分离
HWND并调用
虚函数PostNcDestroy。一些
类重写这个函数到
删除C ++对象。

When destroying a Windows window, the last Windows message sent to the window is WM_NCDESTROY. The default CWnd handler for that message (CWnd::OnNcDestroy) will detach the HWND from the C++ object and call the virtual function PostNcDestroy. Some classes override this function to delete the C++ object.

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中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆