What is the lifetime of the static variable in the c++ function?

Asked 2 years ago, Updated 2 years ago, 132 views

As far as I know, the static variable defined in the scope of the function is initialized only once and remains even after the function ends What is the exact lifetime? When exactly are the constructors and destructors called?

void foo() 
{ 
    static string plonk = "When will I die?";
}

c++ static lifetime

2022-09-21 17:42

1 Answers

The lifetime of the static variable within the function starts when the code is executed for the first time and ends together at the end of the program. And according to the standard, static object's extinction must run in the opposite order to the generated order.

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);
}

Results:

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


2022-09-21 17:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.