Singleton.h 1.3 KB

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