dexterous
dexterous

Reputation: 6526

Why the singleton works here, although a static variable is re-initialized to NULL?

In this example, I expected that the instance was re-initialzed to NULL everytime. Thus, it shouldn't have worked, it should do new everytime. But, it works actually as singleton. Thus,the new is called only once. Why it works? I am confused here.

class Factory_model
{
public:

    static  Factory_model*    Instance(void);

};

Factory_model*    Factory_model::Instance(void)
{
    static Factory_model* instance = NULL;

    if(instance == NULL)
    {
        qDebug()<< "Creating instance now"<<endl;
        instance = new Factory_model;

    }

    return(instance);
}

int main(int argc, char *argv[])
{

   Factory_model *ptr =  Factory_model::Instance();
   Factory_model *ptr2 =  Factory_model::Instance();
   Factory_model *ptr3 = Factory_model::Instance();
}

The output is the following - Creating instance now

Upvotes: 0

Views: 137

Answers (4)

Exceptyon
Exceptyon

Reputation: 1582

also, have a look at this:

Singleton instance declared as static variable of GetInstance method

...every time c++ static variables and singleton are involved, this is a technique you should know

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254691

I expected that the instance was re-initialzed to NULL everytime.

No, static variables are only initialised once, the first time the program reaches the definition (or earlier if, as here, it can be statically initialised).

Of course, you've got a memory leak, and the object creation isn't thread-safe; but this isn't the place for yet another essay about the perils of the Singleton anti-pattern.

Upvotes: 5

Bryan
Bryan

Reputation: 12200

The line:

static Factory_model* instance = NULL;

is only executed once; that is what the keyword static means when you use it on a local variable. The initialisation is not executed every time you enter the function.

See The static keyword and its various uses in C++ or http://www.cprogramming.com/tutorial/statickeyword.html

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 882226

static Factory_model* instance = NULL;

creates a static storage duration variable called instance and initialises it once. You are correct in that a variant without the static keyword would be initialised each time, but the static makes a difference here.

It's effectively the same as if you had declared it outside the function, but with the added bonus of minimising scope (what can see the variable). Creating a static storage duration variable inside the function means that only the function can see/use it (absent any trickiness in publishing a pointer or reference to it), and it maintains its value across function invocations.

Upvotes: 0

Related Questions