Singleton.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #ifndef ANKI_UTIL_SINGLETON_H
  2. #define ANKI_UTIL_SINGLETON_H
  3. namespace anki {
  4. /// @addtogroup util
  5. /// @{
  6. /// This template makes a class singleton
  7. template<typename T>
  8. class Singleton
  9. {
  10. public:
  11. typedef T Value;
  12. // Non copyable
  13. Singleton(const Singleton&) = delete;
  14. Singleton& operator=(const Singleton&) = delete;
  15. // Non constructable
  16. Singleton() = delete;
  17. ~Singleton() = delete;
  18. /// Get instance
  19. static Value& get()
  20. {
  21. return *(instance ? instance : (instance = new Value));
  22. }
  23. private:
  24. static Value* instance;
  25. };
  26. template <typename T>
  27. typename Singleton<T>::Value* Singleton<T>::instance = nullptr;
  28. /// This template makes a class singleton with thread local instance
  29. template<typename T>
  30. class SingletonThreadSafe
  31. {
  32. public:
  33. typedef T Value;
  34. // Non copyable
  35. SingletonThreadSafe(const SingletonThreadSafe&) = delete;
  36. SingletonThreadSafe& operator=(const SingletonThreadSafe&) = delete;
  37. // Non constructable
  38. SingletonThreadSafe() = delete;
  39. ~SingletonThreadSafe() = delete;
  40. /// Get instance
  41. static Value& get()
  42. {
  43. return *(instance ? instance : (instance = new Value));
  44. }
  45. private:
  46. static thread_local Value* instance;
  47. };
  48. template <typename T>
  49. thread_local typename SingletonThreadSafe<T>::Value*
  50. SingletonThreadSafe<T>::instance = nullptr;
  51. /// @}
  52. } // end namespace anki
  53. #endif