#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; }
singleton的实现代码
最新推荐文章于 2020-07-28 19:23:01 发布