1#ifndef CPR_SINGLETON_H
2#define CPR_SINGLETON_H
3
4#include <mutex>
5
6#ifndef CPR_DISABLE_COPY
7#define CPR_DISABLE_COPY(Class) \
8 Class(const Class&) = delete; \
9 Class& operator=(const Class&) = delete;
10#endif
11
12#ifndef CPR_SINGLETON_DECL
13#define CPR_SINGLETON_DECL(Class) \
14 public: \
15 static Class* GetInstance(); \
16 static void ExitInstance(); \
17 private: \
18 CPR_DISABLE_COPY(Class) \
19 static Class* s_pInstance; \
20 static std::mutex s_mutex;
21#endif
22
23#ifndef CPR_SINGLETON_IMPL
24#define CPR_SINGLETON_IMPL(Class) \
25 Class* Class::s_pInstance = nullptr; \
26 std::mutex Class::s_mutex; \
27 Class* Class::GetInstance() { \
28 if (s_pInstance == nullptr) { \
29 s_mutex.lock(); \
30 if (s_pInstance == nullptr) { \
31 s_pInstance = new Class; \
32 } \
33 s_mutex.unlock(); \
34 } \
35 return s_pInstance; \
36 } \
37 void Class::ExitInstance() { \
38 s_mutex.lock(); \
39 if (s_pInstance) { \
40 delete s_pInstance; \
41 s_pInstance = nullptr; \
42 } \
43 s_mutex.unlock(); \
44 }
45#endif
46
47#endif
48