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

后端 未结 5 1245
渐次进展
渐次进展 2020-11-22 03:32

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 lifetim

5条回答
  •  甜味超标
    2020-11-22 03:52

    The lifetime of function static variables begins the first time[0] 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[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.

    Example

    struct emitter {
        string str;
        emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
        ~emitter() { cout << "Destroyed " << str << 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

    [0] Since C++98[2] 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.

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

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

提交回复
热议问题