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;
}
當時一時沒反應過來,用的較多的還是實例化的單體類.這里筆記一下。不過模板類有其自己方便的地方。所以還是有必要的.
posted on 2010-09-10 10:30
小果子 閱讀(1010)
評論(0) 編輯 收藏 引用 所屬分類:
編程語言