1

A coworker and I were discussing about how to make a singleton and it turns out we're doing it differently.

My singleton :

class Singleton
{
public:
    static Singleton* getInstance() 
    {
        if(!instance) instance = new Singleton();
        return instance;
    }
    ~Singleton()
    {
        if(instance) delete instance;
    }

private:
    Singleton() {}
    static Singleton* instance;
};

His singleton :

class Singleton
{
public:
    static Singleton& getInstance() 
    {
        static Singleton instance;
        return instance;
    }
private:
    Singleton() {}
};

These examples are of course simplified for reading purposes. I like his solution because it is shorter and somehow more elegant, but something bugs me...

When his getInstance() method returns the instance, aren't we leaving the scope where it was declared and destorying it? How do you explain it's lifetime beyond the return?

VincentDM
  • 469
  • 6
  • 17

1 Answers1

2

You need to review storage classes in C++. Any object declared as static (or extern) has static storage and gets destructed at the end of program in the reverse order of construction. The order of construction of naked static objects is not deterministic and troublesome, especially in multi threading. Function local static Objects(AKA Scott Meyer's singletons) OTH are ALAP constructed on first call to the owning function, and since C++11 in a magically thread safe manor(ie. no double construction). I would add following declarations to your friend's class to make the singleton actually single:

class Singleton{
    //...
    Singleton(Singleton const&)=delete;
    Singleton(Singleton&&)=delete;
    auto& operator=(Singleton const&)=delete;
    auto& operator=(Singleton &&)=delete;
};
Red.Wave
  • 2,790
  • 11
  • 17