views:

104

answers:

4

If a window is closed (like with sending WM_CLOSE), are the destructors of objects called?

I followed my source code with a break point in that situation, but the compiler doesn't seem to pass through my destructor.

Is the program closed without calling any destructors?

A: 

I'm not too sure I understand, but let's say you've got a window setup with a typical WndProc and you're pumping messages with something akin to:

while (GetMessage(&msg, hwnd, 0, 0) > 0)
{ 
    TranslateMessage(&msg); 
    DispatchMessage(&msg); 
}

When the window finishes (processes WM_DESTROY, after WM_CLOSE posts is handled and called DestroyWindow), this loop will end, and you'll continue normal execution.

In other words, the window isn't anything too special, but while it's up you're pretty much stuck in this loop. You get the same cleanup as always.

GMan
A: 

It depends on what the program does after the windows is closed. If it exits normally (by returning control from main()) - then yes, the destructors will get called, but only of stack-allocated and global objects. If it calls TerminateProcess() they will definitely not get called.

sharptooth
+2  A: 

Normally, not, unless your WindowProc makes it so.

The Window class (e.g. CWnd in ;FC and CWindow in ATL) are distinct entities from the OS' concept of a window (I'll denote as HWND). They have different lifetimes, but they can be "coupled" together using the WNDPROC.

IIRC, MFC will delete CView-derived classes, but not most of the CWindow-derived. Also, ATL's CWindow, by itself won't be destroyed, as it is by default only a one-way attachment (i.e. attaching a CWindow to a HWND usually doesn't subclass the window).

Most of the time, calling the destructor is by another mechanism:

CDialog foo;
foo.DoModal();

When the dialog is closed, the scope where foo is declared will be exited and foos destructor will be called.

Similary, closing the main window will cause the application to exit, tearign down instances on that way.

peterchen
A: 

The objects in Windows (windows, dialogs, controls etc) are separate and distinct from the C++ objects in your program which wrap them. A window or dialog being closed will not delete a C++ object in your program which happens to be associated with it by way of an m_Hwnd member variable.

To put it in MFC terms, think of it this way - if closing a dialog destroyed the CDialog object associated with it, how could you then retrieve the CDialog DDX data associated with the (small d) dialog's controls?

Bob Moore