C++ (Qt)//--------------------------------------------------------------------------// File: a_singleton.h//// Desc: An one-instance class//-------------------------------------------------------------------------- #ifndef A_SINGLETON_H#define A_SINGLETON_H #include <QtGlobal> // disable the warning regarding 'this' pointers being used in// base member initializer list. Singletons rely on this action// #pragma warning(disable : 4355) //--------------------------------------------------------------------------// Name: uSingleton// Desc: A singleton is a type of class of which only one instance may// exist. This is commonly used for management classes used to// control system-wide resources.//-------------------------------------------------------------------------- template <class T>class uSingleton{public: // the singleton must be constructed with a reference to the controlled object //---------------------------------------------------------------------- uSingleton(T& rObject) { Q_ASSERT_X(!s_pInstance, "constructor", "Only one instance of this class is permitted."); s_pInstance = &rObject; } // the singleton accessor //---------------------------------------------------------------------- ~uSingleton() { Q_ASSERT_X(s_pInstance, "destructor", "The singleton instance is invalid."); s_pInstance = 0; } // the singleton accessor //---------------------------------------------------------------------- static T& instance() { if(!s_pInstance) s_pInstance = new T(); Q_ASSERT_X(s_pInstance, "instancing", "The singleton has not yet been created."); return (*s_pInstance); } // delete singleton static void deleteSingleton() { if(s_pInstance) { delete s_pInstance; s_pInstance = 0; } } private: // Data... //---------------------------------------------------------------------- static T* s_pInstance; // Nonexistant Functions... //---------------------------------------------------------------------- uSingleton(const uSingleton& Src); uSingleton& operator=(const uSingleton& Src); };template <class T> T* uSingleton<T>::s_pInstance = 0; #endif // A_SINGLETON_H
MY_CLASS.testFunc();
C++ (Qt)static T* s_pInstance;
C++ (Qt)static QScopedPointer<T> s_pInstance;...template <class T>QScopedPointer<T> uSingleton<T>::s_pInstance;