/** * @file include/ActivMiddleware/Misc/Singleton.h * * @brief Header file for singleton template. */ #if (!defined ACTIV_MISC_SINGLETON_H) #define ACTIV_MISC_SINGLETON_H #include "ActivMiddleware/ActivMiddleware.h" //! Activ namespace. namespace Activ { /** * @brief Singleton template. * * To make a class a singleton, use as follows: * * class MyFactory : public Singleton * { * public: * ... methods and members ... * * MY_LIB_API static MyFactory &GetInstance(); * * private: * // make the destructor private so instances of this object can't be created, other than by Singleton * ~MyFactory(); * * // allow the base access to the destructor * friend class Singleton; * }; * * In the .cpp file, define the GetInstance() function as follows: * * MyFactory &MyFactory::GetInstance() * { * static MyFactory myFactory; * return myFactory; * } * * The singleton can then be used as follows: * * MyFactory::GetInstance().SomeFunction(...); * * The Singleton class will ensure that the singleton instance is constructed before main(). This is a partial fix for * a multithreaded race on construction of the instance; the assumption is that only one thread will be running before main() * is invoked. * * T must be default-constructible. */ template class Singleton : private Boost::noncopyable { protected: /** * @brief Constructor. */ Singleton(); private: class Initializer { public: Initializer(); void Dummy(); }; static Initializer m_initializer; ///< used to ensure GetInstance() is called before main() }; // --------------------------------------------------------------------------------------------------------------------------------- template typename Singleton::Initializer Singleton::m_initializer; // --------------------------------------------------------------------------------------------------------------------------------- template inline Singleton::Singleton() { // ensure the static creator object is instantiated by referencing it m_initializer.Dummy(); } // --------------------------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------------------------- template Singleton::Initializer::Initializer() { (void) T::GetInstance(); } // --------------------------------------------------------------------------------------------------------------------------------- template void Singleton::Initializer::Dummy() { // do nothing } } // namespace Activ #endif // (!defined ACTIV_MISC_SINGLETON_H)