2

I came across the following structure in a C++ library:

In myClass.h

class myClass {
public:
static myClass* Instance();
.
.
private:
static myClass* _instance;
.
.
};

and in myClass.cpp

myClass* myClass::_instance = NULL;

// followed by the all other functions..

myClass::myClass() {
    .
    .
}

myClass* myClass::Instance() {
    if (_instance == NULL) {
        .
        .
    }
    .
    .
}

So what is the use of making the _instance to be NULL pointer outside any function? And when is this line of code executed?

Thank you.

Edit: Adding the main function. And the instance function in myClass.cpp that checks for the value of the pointer. Still don't understand when the pointer get set to NULL though.

int _tmain(int argc, T_CHAR* argv[]) {

myClass* instance = myClass::Instance();

.
.
.

return 0;
}
simplename
  • 717
  • 7
  • 15

5 Answers5

1

I have stumbled upon something like this once. It was something similar to singleton. The reason (as explained by the person doing it) was that he specifically wanted to initialize instance at the first getInstance() function call and he wanted to make sure that the _instance pointer will be at first initialized to NULL (and not some garbage from memory) so that the check

if (_instance == NULL)

in the function works properly.

I am not sure this is the case here, but it's possible.

vetham
  • 116
  • 3
  • Yes, this is exactly the case. Thank you. I'm wondering when does that particular line of code get executed since it is not part of the constructor or any other function? – simplename Oct 01 '14 at 15:28
  • _"It was something similar to singleton."_ Not just "similar to"..! – Lightness Races in Orbit Oct 01 '14 at 15:30
  • @pract: Not in the code you showed us. Probably in some static member function of `myClass`. – Lightness Races in Orbit Oct 01 '14 at 15:31
  • @pract The line of code where myClass::_instance gets initialized is executed before code using it can be executed, i.e., during initialization. See the answers to [this question](http://stackoverflow.com/questions/1421671/when-are-static-c-class-members-initialized) for more details. – ahans Oct 01 '14 at 15:59
1

So what is the use of making the _instance to be NULL pointer outside any function?

Static data members usually have to be defined, in the namespace containing their class, in one source file; they are subject to the One Definition Rule, and so must have exactly one definition in any program that uses them. This is that definition.

Initialising it with NULL makes sure it's initially null, so that the Instance() function can determine whether the instance has been created yet. This isn't strictly necesssary since, like all static variables, it will be zero-initialised whether or not you explicitly provide an initialiser.

And when is this line of code executed?

During static initialisation, before any other code in the program; since it's a trivial type with a constant initialiser.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

Static keyword means it is being shared by all the objects that will be instantiated by the class. Hence you need to initialize it outside any function.Static states that it is a class variable shared between all the instance of the class. It is opposite to instance variables, which each instance has its own copy. To access a class variable, there are two ways. 1) a_class::static_variable 2) a_class a; a.static_variable. The initialization must go in the source file (.cpp) rather than in the header. Because it is a static variable the compiler needs to create only one copy of it. If you don't, you get a link error. If that is in a header you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker.

Static data members are not part of objects of a given class type; they are separate objects. As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope.

lakshmen
  • 28,346
  • 66
  • 178
  • 276
0
myClass* myClass::_instance = NULL;

the code attempts to initialize the static member variable.

Decipher
  • 194
  • 2
  • 11
0

It's an initialisation, ensuring that the pointer starts life with the value NULL from the very beginning of the program.1

It gives the pointer an invalid, but recognisable and testable value before some useful pointer value is assigned to it later on during the program. This way, you can safely test the pointer to see whether it was yet given said useful value.

In this case, since you are showing a singleton, "later" means "when an instance of myClass is first requested" using some myClass::getInstancePlease() function that you have not shown.

It is more common to implement a singleton with a function-static instance, rather than a class-static pointer to some [probably dynamically-allocated] instance.

1 As an object with static storage duration, it would do so anyway; therefore, this initialisation is actually completely pointless beyond documenting programmers' intent.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I'm afraid your footnote is incorrect. If you don't initialize a static data member, it won't default to 0. It will not exist at all and you'll get a link-time error when you try accessing it. – 5gon12eder Oct 01 '14 at 15:31
  • @5gon12eder: [That's total nonsense](http://coliru.stacked-crooked.com/a/6e8db1b25dbbd76c). Where did you hear that?! [You're confusing initialisation for definition](http://coliru.stacked-crooked.com/a/3a384ef6a19548c7). In fact, all static-storage-duration objects are assuredly zero-initialised as a first step at program start-up. – Lightness Races in Orbit Oct 01 '14 at 15:32
  • You are right, it would be correct to say “if you don't *define*” it. What I wanted to say was that if you remove the line that confuses the OP from the code, it will give you a linker error. Therefore, the line is not completely pointless. Writing `int * Test::pointer;` instead of `int * Test::pointer = 0;` would indeed have the same effect. – 5gon12eder Oct 01 '14 at 15:37
  • @5gon12eder: Right, which is what my footnote says! – Lightness Races in Orbit Oct 01 '14 at 15:38
  • Yes, but I'm pretty sure that this requires a level of understanding nuances of the language that is beyond what we can expect from people asking questions like this one. – 5gon12eder Oct 01 '14 at 15:40
  • @5gon12eder: Even if that were true (and I really don't think that it is), it'd be all the more reason to tell them the truth rather than making things up and thereby confusing them further. :) – Lightness Races in Orbit Oct 01 '14 at 15:45
  • I'm sorry if I accidentally happened to offend you which was not my intent. I only wanted to comment that my first thought after reading your footnote was that you meant to say the line in question had no effect, which could have been improved by re-wording it. But the question is now closed as a duplicate, anyway. – 5gon12eder Oct 01 '14 at 15:50
  • @5gon12eder: You certainly did not offend me. It just seems that you've misunderstood some things about static members and/or the meaning of the term "initialisation", as evidenced by a similar comment on one of the other answers that cannot be explained away by accusing the person you replied to of being unclear. :) I notice that you've deleted it now. – Lightness Races in Orbit Oct 01 '14 at 15:51
  • What do you mean by "very beginning of the program"? Thank you to both of you. – simplename Oct 01 '14 at 15:59
  • @pract: #1 All statics are zero-initialised. #2 All static initialisers from your code are executed. #3 `main` is executed. – Lightness Races in Orbit Oct 01 '14 at 16:10