Destructor Invocation for Global and Class Static Variables in C
In C , objects are typically allocated in the stack memory (for local variables) and heap memory (for dynamically allocated variables). However, global variables and class static variables are allocated in the data section of the program, prompting the question: When are their destructors called?
According to the C 03 standard (§ 3.6.3), the destructors for initialized objects with static storage duration are invoked upon returning from the main function and when the exit function is called. These objects are destroyed in the reverse order of their constructor completion or dynamic initialization completion.
Additionally, for class static data members (§ 9.4.2 7), their initialization and destruction behavior is analogous to that of non-local objects.
However, if a destructor has no observable behavior (i.e., performing no side effects), it may not be invoked. This is because the compiler can optimize the code to avoid calling unnecessary destructors, as described in Terry Mahaffey's response to "Is a C destructor guaranteed not to be called until the end of the block?".
The above is the detailed content of When are Destructors Called for Global and Class Static Variables in C ?. For more information, please follow other related articles on the PHP Chinese website!