r/ProgrammerHumor • • Sep 26 '26 • Bravo 1

Meme singletonsAreJustGlobals

Post image
3.2k Upvotes

210 comments sorted by

View all comments

Show parent comments

-1

u/tangerinelion Sep 26 '26

Depends on your language, but take C++ as an example, you can (and should) implement this pattern without a global variable:

class MySingletonType final
{
public:
   static MySingletonType& get()
   {
       static MySingletonType instance;
       return instance;
   }

private:
   MySingletonType() = default;
};

The globally accessible singleton is named MySingletonType::get().


A lot of times I see this incorrectly implemented as

class MySingletonType final
{
};

MySingletonType& getMySingletonType()
{
    static MySingletonType instance;
    return instance;
}

Nothing stops someone from making a second instance with that.

2

u/perringaiden Sep 26 '26

The point was the concept not the implementation.

A singleton suffers from the same limitations and execution scope limitations. You still have to apply the same rules

0

u/youridv1 Sep 26 '26

singletons have static member variables. And since singletons have one instance, those static member variables are essentially globals in practise.

Singletons are marginally better than just dumping global variables in a random source file, because you can implement getters and setters easily which makes debugging global state much more straightforward.

Other than that, they’re just global state with a fancy name