Behaviour of a static member in static function

When you look at the following code, you'll see, there is a static member, which is initialised to be 0, nevertheless, such initialization happens just once for all calls!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

class A
{
public:
   static A *getA()
   {
      static A *a = 0;
      if (!a)
      {
         a = new A;
         cout << "made new \"A\"!" << endl;
      }
      return a;
   }
};

int main(int argc, char **args)
{
   A *a = A::getA();
   a->getA();
   A::getA();
   return 0;
}


Which produces an output like this:
entered function.
made new "A"!
entered function.
entered function.


So my question is: how can that be explained and how can one be sure to use this kind of static member's nature, perhaps in some other cases too?
Static variables have global lifetime, local scope and are initialised on first use. They are given a default value of zero.
Topic archived. No new replies allowed.