C++ 使用模板 实现单例模式

来源:互联网 发布:淘宝网店装修设计师 编辑:程序博客网 时间:2024/05/16 05:13
template<class T>class Singleton{public:    static T* getInstance(){        if(ptr==NULL){            ptr=new T();//(T*)(::operator new(sizeof(T)));        }        return ptr;    }private:    Singleton(){};    static T* ptr;};template<typename T>T* Singleton<T>::ptr=0;class C{public:    int x;    C(){        x=0;    }    ~C(){        cout<<"C delete"<<endl;    }};int main(){    C* c=Singleton<C>::getInstance();    C* d=Singleton<C>::getInstance();    cout<<c<<" "<<d<<endl;}


原创粉丝点击