转载网址:http://blog.csdn.net/windboyzsj/article/details/2790485
1 #include <iostream.h>
2 class Singleton
3 {
4 public:
5 ~Singleton(){cout<<"singleton deconstruct"<<endl;}
6 static Singleton* Instance()
7 {
8 if (_instance == NULL)
9 {
10 _instance =
new Singleton();
11 static Cleaner cl;
//延迟到这里
12 }
13 return _instance;
14 }
15 void Print(
char* str)
16 {
17 cout<<"singleton print:"<<str<<endl;
18 }
19 private:
20 Singleton(){cout<<"singleton construct"<<endl;}
21 static Singleton* _instance;
22 class Cleaner
23 {
24 public:
25 Cleaner(){cout<<"cleaner construct"<<endl;}
26 ~Cleaner()
27 {
28 cout<<"cleaner deconstruct"<<endl;
29 if(Singleton::Instance())
30 delete Singleton::Instance();
31 }
32 };
33 };
34 Singleton* Singleton::_instance = NULL;
35 int main(
int argc,
char* argv[])
36 {
37 Singleton::Instance()->Print("print 1");
38 Singleton::Instance()->Print("print 2");
39 return 0;
40 }