一個用C++寫的可以繼承的單例類

之前參考了一篇文章點擊打開鏈接,但在編譯的過程中總是無法通過。後來在其中陸續找出一些錯誤,並做了部分修改,現在終於可以了。如下


//ISingleton.h文件

#ifndef _ISingleton_H_
#define _ISingleton_H_


#include <memory>
#include <boost\thread.hpp>


template <typename T>
class ISingleton
{
public:
    static T* GetInstance(){
    static boost::mutex s_mutex;
    if (s_instance.get() == NULL)
    {
        boost::mutex::scoped_lock lock(s_mutex);
        if (s_instance.get() == NULL)
        {
s_instance.reset(new T());
        }
        // 'lock' will be destructed now. 's_mutex' will be unlocked.
    }
return  s_instance.get();
};


protected:
    ISingleton() { }
    ~ISingleton() { }


    // Use auto_ptr to make sure that the allocated memory for instance
    // will be released when program exits (after main() ends).
    static std::auto_ptr<T> s_instance;


private:
    ISingleton(const ISingleton&);
    ISingleton& operator =(const ISingleton&);
};


template <typename t>
std::auto_ptr<t> ISingleton<t>::s_instance;


#endif


//MySingleton.h文件

#ifndef MySingleton_H
#define MySingleton_H
#include "ISingleton.h"
#include <iostream>


using namespace std;


class MySingleton : public ISingleton<MySingleton>
{
public:


int Count(){
return ++count;
}
private:
int count;
   // blah blah
   MySingleton()
    {
count=0;
        cout << "Construct MySingleton" << endl;
    };


    ~MySingleton()
    {
        cout << "Destruct MySingleton" << endl;
    };
    friend ISingleton<MySingleton>;
    friend class auto_ptr<MySingleton>;


MySingleton(const MySingleton&){};
MySingleton& operator =(const MySingleton&){};
};
#endif


//測試

int _tmain(int argc, _TCHAR* argv[])
{


MySingleton* s;
s=MySingleton::GetInstance();
cout<<s->Count();
int a;
cin>>a;
return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章