C++中實現singleton(單例模式)的最簡單寫法__C++

來源:互聯網
上載者:User

前幾天看了 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;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.