????????????????????????£?
class Singleton
{
public:
//get ????
static Singleton * getInstance(){
if (NULL == instance) {
lock();
//?ж??????
if (NULL == instance) {
instance = new Singleton();
}
unlock();
}
//?????????????????
return instance;
}
//c++ ???????????????????????????Garbage???????Singleton?????????????????????????????á?
class Garbage
{
public:
~Garbage(){
if (Singleton::instance != NULL) {
cout << "??????????????????" << endl;
delete Singleton::instance;
}
}
};
private:
//???????ж????????????????????????????????????????????????????????????????ó????????????????????????????????????????
static Garbage garbage;
//???????????????
static Singleton *instance;
//?????????й?????
Singleton(){
cout << "?????????????????" << endl;
}
//??????????????????
~Singleton(){
cout << "????????????????????" << endl;
}
//??????????????????У????????????????????????????????????м???
Singleton(const Singleton &copy);
//????????????????е???????????????????
Singleton & operator=(const Singleton &other);
};
//??????????????????????????????????????????????????????????????????
//??????????????????г?????????????????????г????
Singleton::Garbage Singleton::garbage;
//?????instance? null
Singleton * Singleton::instance = NULL;
int main(void)
{
Singleton *a = Singleton::getInstance();
Singleton *b = Singleton::getInstance();
Singleton *c = Singleton::getInstance();
if (a == b) {
cout << "a = b" << endl;
}
return 0;
}
??????????de???????????????
????1????????????????????????ι?????????????????Σ???????????????
????2???????????????????????????????????????????