随心动

C++单件模式及内存释放[转载]

转载网址: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 }

posted on 2013-12-17 04:18 陈志远 阅读(297) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2013年12月>
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

统计

常用链接

留言簿

随笔档案

文章分类

Othor's blog

搜索

最新评论

阅读排行榜

评论排行榜