public class Singleton{public: static Singleton* getInstance() { // The following static will be created once per thread! static Singleton instance; return &instance; }private: Singleton() {}};
public class Singleton{public: static Singleton* getInstance() { if (!m_instance) { m_instance = new Singleton(); } return m_instance; }private: static Singleton* m_instance = NULL; Singleton() {}};
private class SingletonCleaner{ ~SingletonCleaner() { Singleton::getInstance()->dispose(); }}public class Singleton{friend class SingletonCleaner;public: static Singleton* getInstance() { if (!m_instance) { m_instance = new Singleton(); } return m_instance; }private: static Singleton* m_instance = NULL; Singleton() { static SingletonCleaner cleaner; } static void dispose() { if (m_instance) { // Clean up any other used resources here as well delete m_instance; m_instance = NULL; } }};
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.