Singleton template in C ++

I am new and a little ignorant in C ++, and I come across C ++ - code that used a singleton pattern,

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

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

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

+3
source share
3 answers

Why use a pointer? The link is simple and consistent with what I want to do: the alias of the object, not an indication of it. staticdoes not apply to a link, it applies to a function, making it callable without an instance.

(Better yet, why use singleton ?)

+7
source

, . self ( getInstance) , . self.

, getInstance, . .

Monostate, , ,

+2

, , , CFoo. , :

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

.

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

Source: https://habr.com/ru/post/1772778/


All Articles