1

I am fairly new to C++ and I was wondering why we return the pointer of an instance when using a singleton?

I am using the one mentioned here: https://refactoring.guru/design-patterns/singleton/cpp/example

As the getInstance function states we return a pointer of itself, but why? Can someone explain me so I understand the point of it better? Why don't we just return the object itself?

I have a C# background so the pointer story is a bit confusing for me, I googled a lot about it already but I don't really get the sense of it yet.

Jelle Vos
  • 48
  • 8
  • 4
    Sometimes (most times) we return a reference to the instance instead of a pointer. "_Why don't we just return the object itself?_" - We do, in the form of a reference. (Btw, the singleton pattern in the link isn't very good i.m.o) – Ted Lyngmo Dec 15 '20 at 19:07
  • 3
    Related (with some good explanations of what each part is doing): [C++ Singleton design pattern](https://stackoverflow.com/a/1008289/2602718) – scohe001 Dec 15 '20 at 19:10
  • 1
    _"Why don't we just return the object itself?"_ - because in **most cases** when you return an object directly, you are in fact returning a copy of that object, and with singletons that's **usually** precisely the thing you want to avoid. I write most/usually because sometimes objects are designed to be returned by copying - like smart pointers - but in case of singletons, in 99.9% cases that's not it - and more often you return type FOO thinking it's direct FOO and the preprocessor or typedefs silently make it BAR* or BAR& for you.. so well.. I think I said enough. – quetzalcoatl Dec 15 '20 at 19:11
  • 2
    `delete Singleton::GetInstance("All Fall Down");` is an extreme example of stupidity, but I've seen this in a code review with the getting of the instance and it's deletion separated by 10 or 12 lines. Worth noting that the Singleton itself couldn't be saved and was purged completely. Surprisingly hard thing to use right, Singleton. – user4581301 Dec 15 '20 at 19:51
  • 1
    There is a difference in terminology between C# and C++ here. What you return an object in C# this would be equivalent to returning a reference in C++. When you return an object in C++ you are returning an object by "value" which results in the object being copied to the destination. In terms of Singelton better implementations of the singelton pattern in C++ return a reference (not a pointer) this is like returning a C# object. – Martin York Dec 16 '20 at 02:49

0 Answers0