Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 285
user236215 Avatar asked Feb 05 '10 02:02

user236215


People also ask

Are static variables global in C?

A global variable can be accessed from anywhere inside the program while a static variable only has a block scope. So, the benefit of using a static variable as a global variable is that it can be accessed from anywhere inside the program since it is declared globally.

Where are global static variables stored in C?

The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).

What is difference between static global and non static global variable in C?

A global static variable is only available in the translation unit (i.e. source file) the variable is in. A non-static global variable can be referenced from other source files.

What happens when a global variable is declared as static?

A global static variable is one that can only be accessed in the file where it is created. This variable is said to have file scope. In C, the preprocessor directive #define was used to create a variable with a constant value. This still works in C++, but problems could arise.


1 Answers

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

like image 75
outis Avatar answered Sep 19 '22 05:09

outis