Utilities (c + +)--single case (Singleton)
One of the core issues in the implementation of the simple version of the single class is that the new heap objects will not be released , which can create a risk of memory leaks .
Class Singleton
{public
:
//instance pointer
static singleton* instance ()
{
if (!_instance) is obtained by class name
_instance = new Singleton;
return _instance;
}
~singleton ()
{
std::cout << "Singleton::~singleton ()" << Std::endl;
}
Private:
//Prohibit copy
Singleton (const singleton&);
singleton& operator= (const singleton&);
Declare the constructor as private
Singleton ()
{
std::cout << "Singleton::singleton ()" << Std::endl;
}
Static singleton* _instance;
singleton* singleton::_instance = NULL;
int main (int, char**)
{
singleton* S1 = singleton::instance ();
singleton* s2 = singleton::instance ();
Only its constructor
//is invoked and its destructor return 0 is not invoked
;
Law I
We can give a destroy function inside a single instance class to deconstruct the new object, and then call it explicitly on the client.
void Destroy ()
{
delete _instance;
_instance = 0;
}
Law Two
Smart pointers are an important tool for memory management. We encapsulate the class instance pointer with a smart pointer, and we have the effect of releasing heap memory.
#include <iostream> #include <boost\shared_ptr.hpp> class Singleton {public:s Tatic boost::shared_ptr<singleton> Instance () {if (_instance = = 0) _instance = Boost::share
D_ptr<singleton> (new Singleton);
return _instance;
} ~singleton () {std::cout << "Singleton::~singleton ()" << Std::endl;
} private:singleton (const singleton&);
Singleton () {std::cout << "Singleton::singleton ()" << Std::endl;
} singleton& operator= (const singleton&);
Static boost::shared_ptr<singleton> _instance;
};
boost::shared_ptr<singleton> singleton::_instance = NULL;
int main (int, char**) {boost::shared_ptr<singleton> s = singleton::instance ();
boost::shared_ptr<singleton> s2 = singleton::instance ();
return 0; }