Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ different singleton implementations

I usually implement the singleton pattern this way :

class Singleton
{
    public:
        virtual ~Singleton() {}

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

    private:
        Singleton();
        Singleton(const Singleton&);
        Singleton& operator=(const Singleton&);
}

Recently, I ran into this implementation, which is slightly different :

class Singleton
{
    public:
        Singleton();
        virtual ~Singleton() {}

        static Singleton& GetInstance()
        {
            return instance;
        }

    private:
        Singleton(const Singleton&);
        Singleton& operator=(const Singleton&);

        static Singleton instance;
}

Singleton Singleton::instance;

Which implementation is better ?

Isn't it dangerous not to make the constructor private (2nd implementation) ?

Thanks.

like image 637
codeJack Avatar asked Sep 23 '26 02:09

codeJack


2 Answers

There is a difference. In first case instance is initialized on first call of the function. In second case it is initialized when program starts.

If you make a public constructor - It's not a singleton, since it's can be created by anyone

like image 123
Andrew Avatar answered Sep 24 '26 18:09

Andrew


I need not repeat the good point about lazy construction of the singleton made in other answers.

Let me add this:

public:
    Singleton();
    virtual ~Singleton() {}

The designer of this particular class felt a need to allow:

  • derivation from this Singleton class, say the derived class is called DerSingleton
  • DerSingleton can have instances which can be deleted with a pointer to Singleton (so DerSingleton is not a singleton)

Any instance of DerSingleton is also a Singleton instance by definition, so it follows that if DerSingleton is instanciated, Singleton is not a singleton.

So this design asserts two things:

  • this class is a singleton
  • this class is not a singleton
like image 35
curiousguy Avatar answered Sep 24 '26 19:09

curiousguy