domlao
domlao

Reputation: 16029

Singleton pattern in C++

I'm new and a little ignorant in C++ and I encounter a C++ code that used a singleton pattern,

class CFoo
{
 public:
   static CFoo& getInstance()
   {
     static CFoo self;
     return self;
   }

 private:
   CFoo(){}
   ~CFoo(){}
};

I am just confused why return a static reference? Is this a valid code? Why the programmer didn't use a pointer?

Upvotes: 4

Views: 1428

Answers (3)

GManNickG
GManNickG

Reputation: 503913

Why use a pointer? A reference is simple and matches what I want to do: alias an object, not point to it. The static doesn't apply to the reference, it applies to the function, making it callable without an instance.

(Even better, why use a singleton?)

Upvotes: 7

user208608
user208608

Reputation:

If you use a pointer, you have to de-reference the pointer in order to use any overloaded operators implemented by CFoo. If it returned a pointer, the code might look like:

(*(CFoo::getInstance ())) == "comparison overloaded op"

vs.

CFoo::getInstance () == "comparison overloaded op"

Upvotes: 1

Chubsdad
Chubsdad

Reputation: 25497

A static local variable e.g. self once initialized (one first pass through the function getInstance) remains for the entire duration of the program unless explicitly deleted. Therefore it is perfectly safe to return the reference to self.

Note that it is getInstance which is static in the function declaration. Storage class specifiers are not allowed on return types of a function.

I would suggest you to use the Monostate design pattern unless of course the need for Singleton is strongly suggested

Upvotes: 2

Related Questions