单例

1、懒汉式

2、饿汉式

3、加锁

4、双重加锁

5、智能指针

6、模板

 

template <typename T>

class Singleton

{

public:

  static T& getInstance()

  {

    init();

    return instance;

  }

  ~Singleton(){}

private :

  static void init()

  {

    if(0 == instance)

    {

      instance = new T;

      atexit(destroy);//注册destroy函数,当程序结束时,自动调用destroy函数    

    }  

  }  

  static void destroy()

  {

    delete instance;

  }

  Singleton(){}

  Singleton(const T& other){}

  Singleton& operator=(cosnt T& other){}

  static T* instance;

}

template<typename T>

T* Singleton<T>::instance = 0;

posted @ 2017-12-25 17:29  Nice vinke  阅读(94)  评论(0)    收藏  举报