Discussion: All Good Things Must Come to an End
Explore the lifetime and initialization behaviors of global, local, and local static variables in C++. Understand dynamic initialization, object destruction order, and best practices for managing global variables to avoid common pitfalls.
Run the code
Now, it’s time to execute the code and observe the output.
A quick recap
In the Hack the Planet! and Going Global puzzles, we learned about the lifetime and initialization differences between a global variable and a local variable:
In this puzzle, we add two new interesting aspects to the object lifetime:
We no longer initialize the variables to a simple constant; there is a constructor with a side effect.
We introduce a local variable
localStaticwith static storage duration.
So, how does the behavior change when we introduce a constructor and a local static variable?
Global variable
Let’s first consider the global variable global. Like the global variable id we saw previously, it has static storage duration, which means only one instance is alive from its initialization until its destruction at the very end of the program.
We previously saw that the global int id; without an initializer was zero-initialized. We also mentioned that a global with an initializer ...