When are static objects destroyed?
As seen in both examples, static objects are always destroyed at the end of the program whether their scope is local or global. This property allows them to retain their value between multiple function calls and we can even use a pointer to them to access them out of scope.
Static Objects in C++
Prerequisite: Static Keyword in C++
An object becomes static when a static keyword is used in its declaration. Static objects are initialized only once and live until the program terminates. They are allocated storage in the data segment or BSS segment of the memory.
C++ supports two types of static objects:
- Local Static Objects
- Global Static Objects.
Syntax:
Test t; // Stack based object static Test t1; // Static object
The first statement when executes creates an object on the stack means storage is allocated on the stack. Stack-based objects are also called automatic objects or local objects. The second statement creates a static object in the data segment or BSS segment of the memory.