From eaec2c0e7a951da01f7aa581a97cc605924b88c8 Mon Sep 17 00:00:00 2001 From: Riyyi Date: Sun, 5 Sep 2021 10:49:28 +0200 Subject: [PATCH] Util: Add singleton class --- src/util/singleton.h | 50 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/util/singleton.h diff --git a/src/util/singleton.h b/src/util/singleton.h new file mode 100644 index 0000000..7ea4955 --- /dev/null +++ b/src/util/singleton.h @@ -0,0 +1,50 @@ +#ifndef SINGLETON_H +#define SINGLETON_H + +#include + +namespace Util { + +template +class Singleton { +public: + static inline T& the() + { + if (s_instance == nullptr) { + s_instance = new T { s {} }; + } + + return *s_instance; + } + + static inline void destroy() + { + if (s_instance) { + delete s_instance; + } + + s_instance = nullptr; + } + + // Remove copy constructor and copy assignment operator + Singleton(const Singleton&) = delete; + Singleton& operator=(const Singleton&) = delete; + Singleton(Singleton&&) = delete; + Singleton& operator=(Singleton&&) = delete; + +protected: + Singleton() {} + + // Constructor token + struct s {}; + +private: + static T* s_instance; +}; + +template +T* Singleton::s_instance = nullptr; + +} // namespace Util + +#endif // SINGLETON_H