关闭

c++单例模板

标签: c++单例模板
215人阅读 评论(0) 收藏 举报
分类:

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


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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9652次
    • 积分:49
    • 等级:
    • 排名:千里之外
    • 原创:13篇
    • 转载:8篇
    • 译文:0篇
    • 评论:0条
    文章分类