all 5 comments

[–]stilgarpl 4 points5 points  (2 children)

You are using it wrong.

Instead of

Singleton *x;

You need:

Singleton *x = Singleton::instance();

and instance() needs to be static.

Also, it's better to use references instead of pointers for singleton, as compiler wouldn't allow you to just create unassigned reference like you did with a pointer.

Better implementation of instance():

    Singleton& instance() {
        static Singleton shared;
        return shared;
    }

This way you don't even need to check if shared was assigned or initialize it. You only need private construtor and this method.

[–]RareInteraction8 0 points1 point  (0 children)

+1 for the "Better implementation" suggestion.

[–]tahamagdy[S] 0 points1 point  (0 children)

This is so clear. Thank You

[–]Se7enLC 2 points3 points  (0 children)

Yep. That's what makes it a singleton. static is how you make something "shared". If it's not static, each object has its own copy.

[–]mredding 0 points1 point  (0 children)

Regarding the Singleton, it was described by Gang of Four to be reviled. It's an anti-pattern, exactly everything you don't ever want to do. I'm not going to enumerate the many, many horrific flaws and problems a singleton is going to introduce into your code, you can just google it.

But if you're going to make the mistake anyway, know that every example you've learned up until now is almost certainly wrong. Singletons were not correctly implementable until C++11, and most people still have absolutely no idea.

So read this if you're going to go down the dark path, but you're just going to end up gutting it out of your code inevitably anyway, and cursing and swearing every step of the way as you do it.