C++ (Qt)#ifndef SINGLETON_H#define SINGLETON_H #include <stddef.h> template <class T>class Singleton{ static T* _self; static int _refcount;protected: Singleton(){} virtual ~Singleton(){_self = NULL;}public: static T* Instance(); void FreeInst();}; template <class T>T* Singleton<T>::_self = NULL; template <class T> int Singleton<T>::_refcount=0; template <class T>T* Singleton<T>::Instance(){ if(!_self) _self=new T; _refcount++; return _self;} template <class T>void Singleton<T>::FreeInst(){ if(--_refcount==0) delete this;} #endif // SINGLETON_H
C++ (Qt)template <class T>class singleton{public: static T& instance() { std::call_once(m_once_flag, [] { m_instance.reset(new T); }); return *m_instance.get(); } singleton() = delete; singleton(const singleton&) = delete; singleton& operator=(const singleton&) = delete; private: static std::unique_ptr<T> m_instance; static std::once_flag m_once_flag;}; template <class T>std::unique_ptr<T> singleton<T>::m_instance; template <class T>std::once_flag singleton<T>::m_once_flag;
C++ (Qt)template <class T>T& singleton(){ static T instance; return instance;}