c++单例模式

1 /**
 2  *
 3  * 文件名称:singleton.cpp
 4  * 文件标识:见配置管理说明书
 5  * 摘    要:单例模式演示
 6  *
 7  * 版    本:1.0
 8  * 作    者:luwei
 9  * 完成日期:12-12-6
10  *
11  **/
12 #include <iostream>
13 
14 using std::cout;
15 using std::cin;
16 using std::endl;
17 
18 // 单例模式 Singleton 类
19 class Singleton{
20 public:
21     // 获得一个实例,必须为静态成员函数,因为会在存在对象之前调用
22     static Singleton * getInstance(void)
23     {
24         if(NULL == m_ptr)
25         {
26             m_ptr = new Singleton;
27         }
28 
29         return m_ptr;
30     }
31 
32 private:
33 
34     // 构造函数私有,防止实例化任意对象
35     Singleton() {}
36 
37     // 记录对象的地址,必须为静态成员,因为会在存在对象之前使用
38     static Singleton *m_ptr;
39 };
40 
41 // 初始化静态数据成员
42 Singleton *Singleton::m_ptr = NULL;
43 
44 int main(void)
45 {
46     //Singleton a;                                // 错误 
47 
48     Singleton *a = Singleton::getInstance();    // 正确 
49     Singleton *b = Singleton::getInstance();
50     
51     // 其实 a 和 b 指向同一个对象,因为本身自始至终就只能实例化一个对象
52     cout<< a << endl << b <<endl;
53 
54     system("PAUSE");
55     return 0;
56 }

附: http://pan.baidu.com/share/link?shareid=147883&uk=1596008112

c++23种设计模式.pdf

原文链接: https://www.cnblogs.com/luwei-coder/archive/2012/12/06/cppcode-singleton.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/71642

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午2:58
下一篇 2023年2月9日 下午2:58

相关推荐