9

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?

zooropa
  • 3,929
  • 8
  • 39
  • 61
  • 2
    Obvious note: a static variable is, for all intent and purposes, a global variable, with all the woes it incurs, among which: no possible reentrance (testing more difficult), obligation to serialize accesses in multi-threaded code (performance bottleneck), ... Try not to use global variables (and thus singletons) whenever possible. – Matthieu M. Sep 23 '10 at 18:15

3 Answers3

9

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

sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • 2
    This is true also for static variables in functions declared outside of a class scope (free standing functions). It is also true that there is only one instance of the variable per class, but only because the function belongs to the class. The variable is only initialized once, when the function is first called, allowing some control over initialization dependencies. – gregg Sep 23 '10 at 13:24
5

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.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
3

Is is "per class", since it's static to the actual method and there is only one location where that method is, i.e. in the class.

unwind
  • 391,730
  • 64
  • 469
  • 606