开发者

Is local static variable per instance or per class?

开发者 https://www.devze.com 2023-01-17 02:44 出处:网络
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

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;
}
开发者_Go百科

Is listStatic per instance or per class?


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消