What is a single case?
A singleton is a class that can have only one object. For example, in the world in which we live, there is only one planet of life-the Earth (at least so far as the world discovered by humans).
Implementation of a single case
There are many ways to implement a singleton, of course, I will not give you one by one examples of various ways, I will tell the simplest way to achieve, I believe you can easily think of this way:
Singleton.h:
#ifndef __singleton_h__#define __SINGLETON_H__#include <string>//Planet classclassplanet{ Public:Virtual~planet ();Staticplanet* getinstance (Const STD::string& name);STD::stringGetName ();Private: Planet (Const STD::string& name);STD::stringM_name;StaticPlanet* s_pplanet;};#endif //__singleton_h__
Singleton.cpp:
#include "stdafx.h"#include "Singleton.h"conststd::string& name ) : m_name(name){}Planet::~Planet(){}Planet* Planet::GetInstance(conststd::string& name){ if (s_pPlanet == NULL) { new Planet(name); } return s_pPlanet;}std::string Planet::GetName(){ return m_name;}
Isn't it simple? But if it's just that simple, then I'll have to write it.
Have you found a problem: the S_pplanet member created (new) out of the object, but there is no place to release (delete) it. This is dangerous, so that the memory space created by S_pplanet is only released by the operating system when the program finishes exiting the process.
We can not voluntarily release the created program in the program problem is dangerous, even if it does not have any problems, it is an unhealthy program. Then we will make another improvement to the above procedure:
Singleton.h:
#ifndef __singleton_h__#define __SINGLETON_H__#include <string>//Planet classclassplanet{ Public:Virtual~planet ();Staticplanet* getinstance (Const STD::string& name);STD::stringGetName ();Private: Planet (Const STD::string& name);STD::stringM_name;StaticPlanet* s_pplanet;classcgarbo{ Public: ~cgarbo () {if(planet::s_pplanet! = NULL) {DeleteS_pplanet; } } };StaticCgarbo S_carbo;};#endif //__singleton_h__
The garbo above is an internal class with only one function that is dedicated to releasing S_pplanet objects. A static member S_carbo of a Garbo type is defined in the planet class, and the S_carbo object is automatically refactored when the scope of the entire file is exited, and the S_carbo object is disposed when the destructor s_pplanet the object.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permitted not for any commercial use, reproduced please indicate the source.
A single case in life--not single