I see several code examples showing variables and object creations inside of the InitInstance()
function of an MFC appObject (i.e. theApp
). I thought anything created inside a function dies when the function exits. And the InitInstance
function does appear to exit prior to the program exiting, just after showing the windows.
What am I missing? How does this work?
Yes, you are correct: objects created at function scope with automatic storage duration will be automatically destroyed when the function exists.
There are two possible explanations for what you're seeing (it's hard to narrow it down any more than that since you didn't include any example code with your question):
The objects are actually being created using the new
keyword, which means that they have dynamic storage duration and are not automatically destroyed. Instead, they must be manually destroyed using the delete
keyword. In addition to seeing new
, a dead giveaway of this style is the use of pointers—new
returns a pointer to the new object, so you'll see *
all over the place.
The object doesn't actually need to exist any longer than the function in which it is declared. It might be temporarily created just so that some of its member functions can be called. The effects of these member functions are global or have effects beyond the class object itself. This is rather common in MFC, since most of the classes are wrappers around the Win32 API.
For example, the CWnd
class is just an object-oriented wrapper around a Win32 window, represented by an HWND
(or handle to a window). You can create a CWnd
object, use it to create and manipulate a Windows window (HWND
), and then allow it to be destroyed without affecting the underlying Windows window. The "Remarks" section of the CWnd
documentation talks a bit about this confusing behavior:
A
CWnd
object is distinct from a Windows window, but the two are tightly linked. ACWnd
object is created or destroyed by theCWnd
constructor and destructor. The Windows window, on the other hand, is a data structure internal to Windows that is created by aCreate
member function and destroyed by theCWnd
virtual destructor. TheDestroyWindow
function destroys the Windows window without destroying the object.
You did mention the ubiquitous theApp
object in your question, though. That one is a little different—it's actually a global object because it is not declared inside of any function's scope. It is automatically constructed when the program begins executing, and automatically destroyed when the program ends.