Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is local static variable per instance or per class?

Tags:

c++

I want to know if I have a static variable within a class member function if that variable will only have an instance for that class or for each object of that class. Here's an example of what I want to do.

class CTest
{
public:
  testFunc();

};

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

Is listStatic per instance or per class?

like image 753
zooropa Avatar asked Sep 23 '10 12:09

zooropa


2 Answers

It is per that function CTest::testFunc() - each invokation of that member function will use the same variable.

like image 189
sharptooth Avatar answered Oct 27 '22 12:10

sharptooth


Something to get your mind boiling:

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

And in this case, how many counters ?
.
.
.
.
The answer is: as many different T for which Question is instantiated with, that is a template is not a class itself, but Question<int> is a class, different from Question<double>, therefore each of them has a different counter.

Basically, as has been said, a local static is proper to a function / method. There is one for the method, and two different methods will have two different local static (if they have any at all).

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

Here, there are 2 counters (all in all): one is Other::Foo()::M and the other is Other::Bar()::M (names for convenience only).

The fact that there is a class is 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.

like image 28
Matthieu M. Avatar answered Oct 27 '22 11:10

Matthieu M.