File:singleton.hpp
1 #ifndef __SINGLETON_HPP_
2 #define __SINGLETON_HPP_
3
4 template <class T>
5 class Singleton
6 {
7 public:
8 static T* Instance() {
9 if(!m_pInstance) m_pInstance = new T;
10 assert(m_pInstance !=NULL);
11 return m_pInstance;
12 }
13 protected:
14 Singleton();
15 ~Singleton();
16 private:
17 Singleton(Singleton const&);
18 Singleton& operator=(Singleton const&);
19 static T* m_pInstance;
20 };
21
22 template <class T> T* Singleton<T>::m_pInstance=NULL;
23
24 #endif
Usage:
1 #include "singleton.hpp"
2
3 class Logger
4 {
5 public:
6 Logger() {};
7 ~Logger() {};
8 bool openLogFile(string);
9 void writeToLogFile(string);
10 bool closeLogFile(string);
11 private:
12 ...
13 ...
14 };
15
16 bool Logger::openLogFile(std::string)
17 {
18 ...
19 ...
20 }
21
22 ...
23 ...
24
25 typedef Singleton<Logger> LoggerSingleton; // Global declaration
26
27 main()
28 {
29 ...
30
31 LoggerSingleton::Instance()->openLogFile("logFile.txt");
32
33 ...
34 }
来自:http://www.yolinux.com/TUTORIALS/C++Singleton.html
原文链接: https://www.cnblogs.com/good90/archive/2012/08/24/2654113.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/60744
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!