单例的实现(C++)
前面有一篇文章讲单例实现,但是代码有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 }