一个用C++写的可以继承的单例类

来源:互联网 发布:烟台玉兔网络 编辑:程序博客网 时间:2024/06/05 14:18

之前参考了一篇文章点击打开链接,但在编译的过程中总是无法通过。后来在其中陆续找出一些错误,并做了部分修改,现在终于可以了。如下


//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;
}

0 0
原创粉丝点击