简体   繁体   中英

Function static variables initialization

I have a static local variable inside a class non-static function. Will this static function variable be tied with the class instance or it will be initialized just once, regardless of how many instances of this class you create and call this function.

If it's a function static object, then its lifetime is related to the function, not the class of which the function is a member.

You could test this completely trivially:

#include <iostream>

struct Tracked
{
    Tracked() { std::cout << "ctor\n"; }
    Tracked(const Tracked&) { std::cout << "copy\n"; }
    ~Tracked() { std::cout << "dtor\n"; }
};

struct Tester
{
    void foo()
    {
        static Tracked t;
    }
};

int main()
{
    Tester t1;
    Tester t2;

    t1.foo();
    t2.foo();
}

Output:

ctor
dtor

( live demo )

It will be initialized once, the first time you call the function. It's completely independent of any instance lifetimes, and that of the class itself, and those of non-local static variables.

In C++11, this initialization is guaranteed to be thread-safe should the function be called from multiple threads at once. Before that, it varied by compiler. (In particular, local static variable initialization was not thread-safe in MSVC up until VS2015, where they finally implemented this).

A class member function is just an usual function in static memory with hidden argument this . When a class instance calls this function, a pointer to the instance memory (which is your whole instance, rest is compiler magic) is just added to the arguments list for this .

And because your function is static and not some chunk of dynamic memory, your local variable is static too -> initialized just once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM