闲来无事写个单例模板发现没法调用析构函数,测试好久才通过,特记录于此!!!
template <typename T>
class SingletonTemplate
{
public:
static T& getInstance(){
if (SingletonTemplate::m_obj == 0){
SingletonTemplate::m_obj = createInstance();
}
return *(SingletonTemplate::m_obj);
}
protected:
SingletonTemplate(){
assert(m_obj == 0);
m_obj = static_cast<T *>(this);
}
private:
class Garbo
{
public:
~Garbo(){
cout<<"destroy Garbo ..."<<endl;
delete SingletonTemplate<T>::m_obj;
}
void func(){}
};
private:
static inline T* createInstance(){
return new T();
m_garbo.func();
}
private:
static T *m_obj;
static Garbo m_garbo;
};
template <typename T>
T *SingletonTemplate<T>::m_obj = 0;
template <typename T>
typename SingletonTemplate<T>::Garbo SingletonTemplate<T>::m_garbo;
测试Demo如下:
class test
{
public:
test(){cout<<"create test instance...."<<endl;}
~test(){cout<<"destroy test instance...."<<endl;}
void print(){cout<<"pirnt information..."<<endl;}
};
class hello
{
public:
hello(){cout<<"create hello instance****"<<endl;}
~hello(){cout<<"destroy hello instance***"<<endl;}
void print(){cout<<"say hello to everybody***"<<endl;}
};
void func()
{
SingletonTemplate<test>::getInstance().print();
SingletonTemplate<test>::getInstance().print();
SingletonTemplate<hello>::getInstance().print();
SingletonTemplate<hello>::getInstance().print();
}
int main(int argc, char *argv[])
{
func();
return 0;
}