C++单例模板类的实现和使用

为了方便后续单列类自己实现,所以统一写一个单例类的模板:

Singleton.h


#pragma once


#include "stdlib.h"


template
class TSingleton
{
public:
    //create
    static void Create()
    {
        if ( !ms_pObject )
        {
            ms_pObject = new T;
        }
    }


    //destroy
    static void Destroy()
    {
        if ( ms_pObject )
        {
            delete ms_pObject;
            ms_pObject = NULL;
        }
    }


    //get instance
    static T* Get()
    {
Create();
        return ms_pObject;
    }


protected:
    static T* ms_pObject;
};


template 
T* TSingleton::ms_pObject = NULL;


如果有类需要实现为单例,只需要继承TSingleton,例如

class test:public TSingleton

{

}

你可能感兴趣的:(c++)