The idea is to have a Singleton in C++ deleted when the program ends. We learned this method of implementation in class:
class Singleton
{
private:
static Singleton* the_singleton;
protected:
Singleton()
{
static Keeper keeper(this);
/*CONSTRUCTION CODE*/
}
virtual ~Singleton()
{
/*DESTRUCTION CODE*/
}
public:
class Keeper
{
private:
Singleton* m_logger;
public:
Keeper(Singleton* logger):m_logger(logger){}
~Keeper()
{
delete m_logger;
}
};
friend class Singleton::Keeper;
static Singleton* GetInstance();
{
if (!the_singleton)
the_singleton = new Singleton();
return the_singleton;
}
};
Singleton* Singleton::the_singleton = NULL;
The idea is that on the first time the Singleton is created, a static Keeper object will be created in the Singleton's C'tor, and once the program ends, that Keeper will be destroyed, and in turn will destroy the Singleton's instance it is pointing to.
Now, this method seems quite cumbersome to me, so I suggested to ditch the keeper class and make the Singleton's instance a static object of the getInstance method:
<!-- language: c++ -->
class Singleton
{
protected:
Singleton()
{
/*CONSTRUCTION CODE*/
}
~Singleton()
{
/*DESTRUCTION CODE*/
}
public:
static Singleton &getInstance()
{
static Singleton instance;
return instance;
}
/*OBJECT FUNCTIONALITY*/
};
That way, the Singleton is constructed on the first call to the getInstance method, and destroyed once the program ends. No need for that keeper class.
I tested it and it worked just fine - the Singleton was created and destroyed at the right places. However, my TA said that this pattern is wrong, though he couldn't recall what exactly was the problem with it. So I'm hoping someone here has encountered this implementation before and can tell me what's wrong with it.