Is there a local static variable for each instance or for each class?

I want to know if I have a static variable inside a member function of a class if this variable will only have an instance for this class or for every object of this class. Here is an example of what I want to do.

class CTest { public: testFunc(); }; CTest::testFunc() { static list<string> listStatic; } 

Is listStatic for each instance or for class?

+4
source share
3 answers

This is for this function CTest::testFunc() - each involution of this member function will use the same variable.

+9
source

Something to make your mind boil:

 template <typename T> struct Question { int& GetCounter() { static int M; return M; } }; 

And in this case, how many counters?
.
.
.
.
Answer: there are so many different T for which Question is created, and not the class itself, but Question<int> is a class other than Question<double> , so each of them has a different counter.

In principle, as already mentioned, the local static method is correct for the function / method. There is one method, and two different methods will have two different local static ones (if any).

 struct Other { int& Foo() { static int M; return M; } int& Bar() { static int M; return M; } }; 

There are 2 counters (total): one is Other::Foo()::M , and the other is Other::Bar()::M (names are for convenience only).

The fact that there is a class is an accessory:

 namespace Wazza { int& Foo() { static int M; return M; } int& Bar() { static int M; return M; } } 

Two other counters: Wazza::Foo()::M and Wazza::Bar()::M

+5
source

Is is "for every class" because it is static for the actual method and there is only one place where this method is, i.e. in class.

+2
source

All Articles