Does C++ call destructors for global and class static variables?

user236215 picture user236215 · Feb 5, 2010 · Viewed 39.3k times · Source

From my example program, it looks like it does call the destructors in both the cases. At what point does it call the destructors for global and class-static variables since they should be allocated in the data section of the program stack?

Answer

outis picture outis · Feb 5, 2010

From § 3.6.3 of the C++03 standard:

Destructors (12.4) for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit (18.3). These objects are destroyed in the reverse order of the completion of their constructor or of the completion of their dynamic initialization. If an object is initialized statically, the object is destroyed in the same order as if the object was dynamically initialized. For an object of array or class type, all subobjects of that object are destroyed before any local object with static storage duration initialized during the construction of the sub- objects is destroyed.

Furthermore, § 9.4.2 7 states:

Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).

However, if a destructor has no observable behavior, it may not be invoked. Terry Mahaffey details this in his answer to "Is a C++ destructor guaranteed not to be called until the end of the block?" .