How many instances of static variables declared in a method exist?

In this case, there should be only one or zero instance of the static variable. It depends on whether the call to f() or not.

 void f() { static int a; } 

But how many instances of a static variable are there if f() is a method?

 class A { void f() { static int a; } }; 
+6
source share
2 answers

Same as function: 0 or 1. It is also very easy to check:

 class A { public: void f() { static int a = 0; ++a; cout << a << endl; } }; int main() { A a; af(); af(); A b; bf(); } 

Conclusion:

 1 2 3 

However, if you obsess with class A and make the function virtual, like this:

 class A { public: virtual void f() { static int a = 0; ++a; cout << a << endl; } }; class B:public A { public: void f() { static int a = 0; ++a; cout << a << endl; } }; 

then the variable a will be different for the base and for each derived class (because the functions are also different).

+4
source

Same thing ... being a member function orthogonal to a static local.

+2
source

Source: https://habr.com/ru/post/919818/


All Articles