常用的单例类模板

来源:互联网 发布:nginx访问静态资源403 编辑:程序博客网 时间:2024/05/02 04:23

#ifndef _SingletonTemplate_h#define _SingletonTemplate_htemplate <class T>class SingletonTemplate{public:    static T *getInstance()    {        if(NULL == _instance)        {            _instance = new T();        }        return _instance;    }        static void deleteInstance()    {        if(NULL != _instance)        {            delete _instance;            _instance = NULL;        }    }    private:    static T *_instance;};template <class T>T *SingletonTemplate<T>::_instance = NULL;#endif

创建单例类:MyClass如下

class MyClass : public SingletonTemplate<MyClass>
{
}
要使用的方法放在MyClass类里面即可,记得在程序退出的时候调用deleteInstance()方法,否则会内存泄露。



0 0