Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Where to delete m_pMainWnd

Status
Not open for further replies.

GEAK

Instructor
Feb 1, 2001
90
US
I've been out of programming for a few years, just recently loaded VS2005 onto a system and decided to try getting my feet wet. I've got an MFC app that I'm working on and I'm stuck with a memory leak that I can't seem to resolve.
In the app class I'm reading command line arguments to determine whether to display a dialog or window. My InitInstance function contains code something like this:
Code:
[green]//...[/green]
BOOL bRetVal = FALSE;
CMyWnd* pWnd = NULL;
CMyDlg dlg;
[blue]if[/blue](bDialog)
{
    m_pMainWnd = &dlg;
    dlg.DoModal();
}
[blue]else[/blue]
{
    pWnd = [blue]new[/blue] CMyWnd;
    m_pMainWnd = pWnd;
    [green]//Overridden create function[/green]
    pWnd->Create(NULL);
    RetVal = TRUE;
}
[blue]return[/blue] RetVal;
I'm certain that I've used similar code to this in the past and I never had a memory leak. I'm also fairly certain that it required a delete call in the event that I'm using dynamic memory allocation for CWnd derived class rather than the dialog. The problem I've run into is I can't figure out where to put the delete. I've tried a [tt][blue]delete this[/blue];[/tt] in the window's destructor and I've tried deleting m_pMainWnd in the app's ExitInstance but neither does anything (as a matter of fact, by the time the ExitInstance function is called m_pMainWnd is NULL).
I'm sure I'm missing something simple but I just can't see or remember what it is. Any suggestions?
 
The problem you have here is that if it is a dialog and you delete it you will get a crash. In one instance, it points to something that gets deleted automatically when it goes out of scope. In the other instance, it hangs around until you've finished.

Options are

1) Don't worry about it - it is just one leak, only occurs once and only when the program is about to die. Does it really matter? It is like worrying about the price of crude oil when you are about to die.
2) You could delete it in an ExitInstance, which is the opposite of InitInstance

If you are going to delete it, set m_pMainWnd = 0 after dlg.DoModal so that if it goes into ExitInstance, and gets deleted, it won't crash.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top