Tuesday, March 30, 2010

CDialog::PostNcDestroy and delete this

Whenever I dynamically create a CDialog object, I like to let it clean itself up by adding the following code:

void CMyDlg::PostNcDestroy()
{
CDialog::PostNcDestroy();
delete this;
}

PostNcDestroy is a virtual function from CDialog that is called after DestroyWindow. Typically you are done with a CDialog object after the window is destroyed so it is nice to let itself clean itself up. Essential the entire CDialog object becomes a free smart pointer.

Another nice trick is if you are calling the same CMyDlg object statically you can execute the following code and be ok...

{
CMyDlg dlg();
dlg.DoSomething();
....
}

and then let the object go out of scope.

BE CAREFUL though, if you called destroy window unnecessarily.

dlg.DestroyWindow(); //Oops

Then you are going to corrupt your heap and delete a static object.

Instead just hide the window until it goes out of scope.

No comments:

Post a Comment