The idea is for Singleton in C ++ to be deleted when the program terminates. We learned this implementation method in the class:
class Singleton
{
private:
static Singleton* the_singleton;
protected:
Singleton()
{
static Keeper keeper(this);
}
virtual ~Singleton()
{
}
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 for the first time a Singleton is created, a static Keeper object will be created in Singleton C'tor, and as soon as the program is finished, this Keeper will be destroyed and, in turn, destroy the Singleton instance it points to.
Now this method seems rather cumbersome to me, so I suggested to break the keeper class and make the Singleton instance a static object of the getInstance method:
<!-- language: c++ -->
class Singleton
{
protected:
Singleton()
{
}
~Singleton()
{
}
public:
static Singleton &getInstance()
{
static Singleton instance;
return instance;
}
};
Thus, Singleton is created the first time the getInstance method is called and destroyed after the program terminates. No need for this keeper class.
, - . , TA , , , . , - , .