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

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


你可能感兴趣的:(C++ 使用模板 实现单例模式)