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
?