前面有一篇文章讲单例实现,但是代码有bug。
新的实现方法如下:
Singleton.h
View Code
1 #ifndef _SINGLETON_H_
2 #define _SINGLETON_H_
3
4 class Singleton
5 {
6 public:
7 int getValue();
8 static Singleton* Instance();
9 private:
10 Singleton();
11 //Singleton(const Singleton& inst);//赋值拷贝函数此处不再需要,因为析构函数为私有,类外无法生成实例
12 //Singleton& operator=(const Singleton& inst);
13
14 ~Singleton();
15
16 int _iValue;
17 };
18 #endif
Singleton.cpp
View Code
1 #include "Singleton.h"
2 #include <cstdlib>
3
4 Singleton::Singleton()
5 {
6
7 }
8 Singleton::~Singleton()
9 {
10
11 }
12 Singleton* Singleton::Instance()
13 {
14 static Singleton m_Singleton;//避免了删除对象的操作,否则还要单独搞个删除对象的函数,因为析构函数不会被调用
15 return &m_Singleton;
16 }
17 int Singleton::getValue()
18 {
19 return _iValue;
20 }
Main.cpp
View Code
1 #include "Singleton.h"
2 #include <cstdlib>
3
4 int main(int argc, char** argv)
5 {
6 int value = Singleton::Instance()->getValue();
7 return EXIT_SUCCESS;
8 }
原文链接: https://www.cnblogs.com/fixer/archive/2013/04/18/3027637.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/85138
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!