singleton的实现代码

来源:互联网 发布:怎么进入淘宝分销平台 编辑:程序博客网 时间:2024/05/16 07:53
#include <iostream>#include <fstream>#include <boost/shared_ptr.hpp>using namespace std;template<typename T>class Singleton{public:    static T* Instance()    {       if(ObjectPtr.get()==NULL)            ObjectPtr.reset(new T());        return ObjectPtr.get();    }protected:    Singleton()    {    }    ~Singleton()    {    }private:    static boost::shared_ptr<T> ObjectPtr;};class Object:public Singleton<Object>{    int Count = 0;private:    Object()    {        Count = 0;        cout<<"Object Created"<<endl;    }    ~Object()    {        cout<<"Object Destroyed"<<endl;    }public:    void SetValue(int value)    {        Count = value;    }    int GetValue()    {        return Count;    }    friend class Singleton<Object>;    friend void boost::checked_delete<Object>(Object* x);};template<>boost::shared_ptr<Object>   Singleton<Object>::ObjectPtr = boost::shared_ptr<Object>();boost::shared_ptr<int> ObjPtr();int main(){    Object* pObject1 = Object::Instance();    Object* pObject2 = Object::Instance();    cout<<pObject1->GetValue()<<" "<<pObject2->GetValue()<<endl;    pObject1->SetValue(5);    cout<<pObject1->GetValue()<<" "<<pObject2->GetValue()<<endl;    pObject2->SetValue(4);    cout<<pObject1->GetValue()<<" "<<pObject2->GetValue()<<endl;    return 0;}


                                             
0 0