Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 227
domlao Avatar asked Dec 28 '22 05:12

domlao


2 Answers

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?)

like image 83
GManNickG Avatar answered Jan 08 '23 05:01

GManNickG


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

like image 38
Chubsdad Avatar answered Jan 08 '23 06:01

Chubsdad