Home  >  Article  >  Backend Development  >  When are destructors invoked for global and class-static variables in C ?

When are destructors invoked for global and class-static variables in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-07 14:12:03290browse

When are destructors invoked for global and class-static variables in C  ?

Destruction of Global and Class Static Variables in C

In C , destructors are typically associated with dynamically allocated objects, but does this behavior extend to globally and class-statically declared variables? To clarify this issue, let's delve into the specifics.

Firstly, it is essential to comprehend that global and class-static variables are typically allocated in the data section of the program's memory rather than the stack, where local variables reside. This distinction raises the question: When are destructors invoiced for these variables?

According to the C 03 standard (section § 3.6.3), destructors for initialized static storage duration objects (those declared at block scope or namespace scope) are invoked when exiting the main function or calling exit. These objects are destroyed sequentially, starting with the most recently initialized and ending with the earliest. This behavior applies to both statically and dynamically initialized objects.

Additionally, section § 9.4.2 7 specifies that static data members are initialized and destroyed in the same manner as non-local objects. However, it's worth noting that destructors with no observable behavior might not be invoked.

The above is the detailed content of When are destructors invoked for global and class-static variables in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn