开发者

Singleton pattern in C++

开发者 https://www.devze.com 2023-01-23 10:30 出处:网络
I\'m new and a little ignorant in C++ and I encounter a C++ code that used a singleton pattern, class CFoo

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开发者_C百科? Is this a valid code? Why the programmer didn't use a pointer?


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


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


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消