1. A Hungry man mode:
#include <iostream>
using namespace std;
Class Singleton {public
:
static singleton& getinst (void) {return
s_inst;
}
Private:
Singleton (void) {}
Singleton (const singleton&);
Static Singleton s_inst;
Singleton Singleton::s_inst;
int main (void) {
singleton& S1 = Singleton::getinst ();
singleton& s2 = Singleton::getinst ();
singleton& s3 = Singleton::getinst ();
cout << &s1 << ' << &s2 << ' << &s3 << Endl;
return 0;
}
2. Lazy mode
#include <iostream>
using namespace std;
Class Singleton {public
:
static singleton& getinst (void) {
if (! M_inst)
m_inst = new Singleton;
++M_CN;
return *m_inst;
}
void Releaseinst (void) {
if (m_cn &&--m_cn = 0)
delete this;
}
Private:
Singleton (void) {
cout << "constructed:" << this << Endl;
}
Singleton (const singleton&);
~singleton (void) {
cout << "destructor:" << this << Endl;
M_inst = NULL;
}
Static singleton* M_inst;
static unsigned int m_cn;
singleton* singleton::m_inst = NULL;
unsigned int singleton::m_cn = 0;
int main (void) {
singleton& S1 = Singleton::getinst ();
singleton& s2 = Singleton::getinst ();
singleton& s3 = Singleton::getinst ();
cout << &s1 << ' << &s2 << ' << &s3 << Endl;
S3.releaseinst ();
S2.releaseinst ();
S1.releaseinst ();
return 0;
}
The difference between two modes: there is only one static variable in the lazy mode, one variable that is returned once by the Getinst function. Lazy mode inside the maintenance of a static pointer variable and a static variable to do the counter, each time the tune will first judge if there is no construction, if the construction of M_inst is not empty, the counter directly + + is good, call the destructor is to judge the counter, no one used to release this memory.