patterncppCritical
What is the lifetime of a static variable in a C++ function?
Viewed 0 times
functionlifetimethevariablestaticwhat
Problem
If a variable is declared as
static in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called?void foo()
{
static string plonk = "When will I die?";
}Solution
The lifetime of function
Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[2], and the order of construction may depend on the specific program run, the order of construction must be taken into account.
Example:
-
In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.
static variables begins the first time[1] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[2], and the order of construction may depend on the specific program run, the order of construction must be taken into account.
Example:
#include
struct emitter
{
string location;
emitter(const string & s): location(s)
{
std::cout
Output:
C:> sample.exe
Created in foo
Destroyed in foo
C:> sample.exe 1
Created in if
Created in foo
Destroyed in foo
Destroyed in if
C:> sample.exe 1 2
Created in foo
Created in if
Destroyed in if
Destroyed in foo
References:
-
Since C++98[3] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.
-
C++98 section 3.6.3.1` [basic.start.term]-
In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.
Context
Stack Overflow Q#246564, score: 309
Revisions (0)
No revisions yet.