c++staticlifetime

What is the lifetime of a static variable in a C++ function?


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 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 <iostream>
    
    struct emitter
    {
        string location;
        
        emitter(const string & s): location(s)
        {
            std::cout << "Created " << location << std::endl;
        }
        
        ~emitter()
        {
            std::cout << "Destroyed " << location << std::endl;
        }
    };
    
    void foo(bool skip_first)
    {
        if (!skip_first)
            static emitter a("in if");
        static emitter b("in foo");
    }
    
    int main(int argc, char * [])
    {
        foo(argc != 2);
        if (argc == 3)
            foo(false);
    }
    

    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:

    1. 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.

    2. C++98 section 3.6.3.1 [basic.start.term]

    3. In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.