1

Can anyone please advise what does following code mean? It looks like singleton pattern but uses & instead of pointer.

class Class
{
 public:
 static Class &Function();
}

Class &Class::Function()
{
 static Class class1;
 return class1;
}
user2864740
  • 60,010
  • 15
  • 145
  • 220
OW Opex
  • 13
  • 2
  • Yes, it is a singleton pattern. I updated the title, as the more focused/relevant question is really _why_ a reference vs a pointer. Or, maybe not. – user2864740 May 12 '20 at 02:34
  • Lots of reading in https://stackoverflow.com/q/1008019/2864740 – user2864740 May 12 '20 at 02:36
  • Welcome to stack overflow. It defines the class as `static` meaning that once it's instantiated, it's there forever. It won't create it again. If you didn't use `static`, you would get a new class every time. The ampersand means return a reference to it. If you didn't do that, you'd get a shallow copy of the class. – Andy May 12 '20 at 03:23

1 Answers1

0

Singleton is an idea made by programmers. It means that it holds no specified form behind it (especially dealing with c++ pointers and references) and only has it's set of rules. The code you see infront of you meant to create a static variable when the function is called and keep it till the end of the whole program comes. Returning it by pointer of reference doesn't matter. It just holds a specified single object which won't be destroyed after the end of the scope (because of the static declaration) and will return only that object. Of course you may just put it as a private variable and return it whenever somebody is going to call the function. But, it always depends on the user it self. Pay your attention to this question: Difference between Singleton implemention using pointer and using static object

Sean Tashlik
  • 176
  • 8