c++单例模板

闲来无事写个单例模板发现没法调用析构函数,测试好久才通过,特记录于此!!!


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


阅读更多
文章标签: c++ 单例模板
个人分类: c++
上一篇解决QWidget父对象加入QGraphicsView内导致当前对象接收不到鼠标移动事件问题
下一篇Qt 5.x 多点触摸配置
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭