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

C++Global VariablesDestructor

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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?" .

Solution 2 - C++

Somewhere after "main"

(you can't know or rely on the exact order in which they are called)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser236215View Question on Stackoverflow
Solution 1 - C++outisView Answer on Stackoverflow
Solution 2 - C++Vi.View Answer on Stackoverflow