Home > Backend Development > C++ > Do C Destructors Get Called for Global and Static Variables?

Do C Destructors Get Called for Global and Static Variables?

DDD
Release: 2024-11-06 13:22:02
Original
465 people have browsed it

Do C   Destructors Get Called for Global and Static Variables?

Does C Call Destructors for Global and Class Static Variables?

Contrary to some assumptions, C does indeed call destructors for both global and class-static variables. Their destruction occurs at two specific junctures:

  1. Upon Returning from Main: When the main() function concludes, all global and class-static variables are destroyed. This accords with § 3.6.3 of the C 03 standard, which mandates this destruction "as a result of returning from main."
  2. Upon Calling Exit: If the exit() function is employed within your program, it triggers the destruction of global and class-static variables "as a result of calling exit," as outlined in § 3.6.3.

It's noteworthy that the order of destruction for these variables mirrors the reverse order of their constructor or dynamic initialization. Furthermore, per § 9.4.2 7, static data members are initialized and destroyed identically to non-local objects.

However, it's important to note that destructors with no observable behavior may not be invoked. This is further explored 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 Do C Destructors Get Called for Global and Static Variables?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template