Before we close out the chapter, we need to tie up one loose end. All the programs presented thus far have created a window with the statement
m_pMainWnd = new CMainWindow; |
in InitInstance. Since the object is instantiated with new, it remains in memory after InitInstance ends and, in fact, will not go away until it is deleted with a delete statement. Yet nowhere in the programs' source code will you find such a statement. On the surface, this would seem to be a problem. After all, every C++ programmer knows that every new must be countered with a delete or objects will be left behind in memory. So what gives?
As you probably suspected, the class library deletes the object for you. To be more precise, the object deletes itself. The key to this little trick is that the very last message a window receives before it goes away for good is WM_NCDESTROY. If you look at the source code for CWnd::OnNcDestroy, you'll see that it calls a virtual function named PostNcDestroy. CFrameWnd overrides PostNcDestroy and executes a
delete this; |
statement. Therefore, when a frame window is destroyed, the object associated with that window is automatically deleted, too. A frame window is destroyed when the user closes the application.
It's worth noting that CWnd's own implementation of PostNcDestroy does not delete the associated window object. Therefore, if you derive your own window class directly from CWnd, you also need to override PostNcDestroy in the derived class and execute a delete this statement. Otherwise, the CWnd object will not be properly deleted. You'll see what I mean in the next chapter.