Home > Backend Development > C++ > body text

When are Destructors Called for Global and Class Static Variables in C ?

Patricia Arquette
Release: 2024-11-07 14:39:03
Original
331 people have browsed it

When are Destructors Called for Global and Class Static Variables in C  ?

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!