对于这样创建的窗口:
void CTestDlgDlg::OnOK()
{
CAutoRelease* pDlg = new CAutoRelease;
pDlg->CreateWnd( this );
}
其中:CAutoRelease继承自CDialog
pDlg是局部变量。因此CAutoRelease只能自己回收自己。
通常的做法是重载CDialog::PostNcDestroy:
void CAutoRelease::PostNcDestroy()
{
CDialog::PostNcDestroy();
delete this;
}
突发奇想,可不可以把delete this,提前呢?比如这样:
void CAutoRelease::OnOK()
{
CDialog::OnOK();
delete this;
}
编译,运行都是OK的,不过输出里面却有警告:
Warning: calling DestroyWindow in CDialog::~CDialog --
OnDestroy or PostNcDestroy in derived class will not be called.
也就是说,在OnOk中调用delete this,是可以回收自己的。
但是,这不是正确的销毁窗口流程,会导致子类中的OnDestroy或PostNcDestroy不被调用。
正确的做法,应该在窗口销毁之后,再回收窗口对象类。即重载CWnd::PostNcDestroy。
这也是MSDN推荐的做法:
CWnd::PostNcDestroy
Called by the default OnNcDestroy member function after the window has been destroyed.
Remarks
Derived classes can use this function for custom cleanup such as the deletion of the this pointer.