emsApplication/sdk/include/hv/singleton.h

37 lines
978 B
C
Raw Normal View History

2024-05-24 12:23:42 +08:00
#ifndef HV_SINGLETON_H_
#define HV_SINGLETON_H_
#include <mutex>
#define DISABLE_COPY(Class) \
Class(const Class&) = delete; \
Class& operator=(const Class&) = delete;
#define SINGLETON_DECL(Class) \
public: \
static Class* instance(); \
static void exitInstance(); \
private: \
DISABLE_COPY(Class) \
static Class* s_pInstance; \
2024-05-24 12:29:09 +08:00
static std::once_flag s_initFlag; \
2024-05-24 12:23:42 +08:00
static std::mutex s_mutex;
#define SINGLETON_IMPL(Class) \
Class* Class::s_pInstance = NULL; \
2024-05-24 12:29:09 +08:00
std::once_flag Class::s_initFlag; \
2024-05-24 12:23:42 +08:00
std::mutex Class::s_mutex; \
Class* Class::instance() { \
2024-05-24 12:29:09 +08:00
std::call_once(s_initFlag, []() {s_pInstance = new Class;}); \
return s_pInstance; \
2024-05-24 12:23:42 +08:00
} \
void Class::exitInstance() { \
2024-05-24 12:29:09 +08:00
std::lock_guard<std::mutex> lock(s_mutex); \
if (s_pInstance) { \
2024-05-24 12:23:42 +08:00
delete s_pInstance; \
2024-05-24 12:29:09 +08:00
s_pInstance = nullptr; \
} \
2024-05-24 12:23:42 +08:00
}
#endif // HV_SINGLETON_H_