Singleton.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (C) 2009-2023, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Util/StdTypes.h>
  7. #include <AnKi/Util/Assert.h>
  8. #include <utility>
  9. namespace anki {
  10. #if ANKI_ENABLE_ASSERTIONS
  11. extern I32 g_singletonsAllocated;
  12. #endif
  13. /// @addtogroup util_patterns
  14. /// @{
  15. /// If class inherits that it will become a singleton.
  16. template<typename T>
  17. class MakeSingleton
  18. {
  19. public:
  20. ANKI_FORCE_INLINE static T& getSingleton()
  21. {
  22. return *m_global;
  23. }
  24. template<typename... TArgs>
  25. static T& allocateSingleton(TArgs... args)
  26. {
  27. ANKI_ASSERT(m_global == nullptr);
  28. m_global = new T(args...);
  29. #if ANKI_ENABLE_ASSERTIONS
  30. ++g_singletonsAllocated;
  31. #endif
  32. return *m_global;
  33. }
  34. static void freeSingleton()
  35. {
  36. if(m_global)
  37. {
  38. delete m_global;
  39. m_global = nullptr;
  40. #if ANKI_ENABLE_ASSERTIONS
  41. --g_singletonsAllocated;
  42. #endif
  43. }
  44. }
  45. static Bool isAllocated()
  46. {
  47. return m_global != nullptr;
  48. }
  49. private:
  50. static inline T* m_global = nullptr;
  51. };
  52. /// @}
  53. } // end namespace anki