前幾天看了 Java中實現singleton的寫法,就想在C++中實現一下,找了很多資料,看了各個牛人寫的不同版本,但最後在stack overflow上找到了一個最簡單的寫法,不需要判斷是否已經有執行個體存在,則在多線程的情況也可以正常使用,現在貼出來以供參考:
class S{ public: static S& getInstance() { static S instance; return instance; } private: S() {}; // Constructor S(S const&); // Don't Implement void operator=(S const&); // Don't implement};它其實是使用了C++中成員函數的靜態變數的特點:靜態局部變數在第一次使用時初始化,並不會銷毀直到程式退出。
具體資料:http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function
下面是我總結的四種singleton在C++中的實現方法:
// Singleton.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include <stdio.h>#include <Windows.h>using namespace std;//C++ Singleton Version 1class Singleton1{private:Singleton1(){};static Singleton1* instance;virtual ~Singleton1(void){}public:int ia;static Singleton1* GetInstance(){if (NULL == instance){instance = new Singleton1();}return instance;}};//Must define static member, not just declarationSingleton1* Singleton1::instance = NULL;//C++ Singleton Version 2//Use smart point to release memory#include <memory>using namespace std;class Singleton2{public:static Singleton2 * GetInstance(){if (NULL == instance.get()){instance.reset(new Singleton2());}return instance.get();}int ia;private:static shared_ptr<Singleton2> instance;};shared_ptr<Singleton2> Singleton2::instance;//C++ Singleton Version 3//Use template to reduce some duplicate worktemplate <class T>class Singleton{public:static T* GetInstance();private:Singleton(){}~Singleton(){}Singleton(const Singleton&){}Singleton& operator=(const Singleton&){}static shared_ptr<T> instance;};template <class T>shared_ptr<T> Singleton<T>::instance;template <class T>T* Singleton<T>::GetInstance(){if (NULL = instance.get()){instance.reset(new Singleton());}return instance.get();}//C++ Singleton Version 4//Avoid memory allocationclass Singleton4{public:static Singleton4& GetInstance(){// Guaranteed to be destroyed.// Instantiated on first use.// Static variable lifetime in function-http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-functionstatic Singleton4 instance;return instance;}private:Singleton4(){}~Singleton4(){}// Dont forget to declare these two. You want to make sure they// are unaccessable otherwise you may accidently get copies of// your singleton appearing.Singleton4(Singleton4 const&);//Don't Implementvoid operator=(Singleton4 const&);//Don't Implement};int _tmain(int argc, _TCHAR* argv[]){/* version 1: Memory leakSingleton1* a = Singleton1::GetInstance();a->ia = 100;Singleton1* b = Singleton1::GetInstance();cout << b->ia << endl;*/Singleton2* a2 = Singleton2::GetInstance();a2->ia = 200;Singleton2* b2 = Singleton2::GetInstance();cout << b2->ia << endl;OutputDebugString(_T("hello world!"));system("pause");return 0;}