让C++的类实现单例模式的宏定义

[复制链接]
 楼主| keer_zu 发表于 2022-9-15 14:14 | 显示全部楼层 |阅读模式
C++, ST, AN, ce, TI, ic
  1. #define DECLARE_SINGLETON(classname)                                      \
  2. public:                                                                  \
  3.   static classname *Instance(bool create_if_needed = true) {              \
  4.     classname **instance = GetInstancePtrAddr();                          \
  5.     if (!*instance && create_if_needed) {                                 \
  6.       static std::once_flag flag;                                         \
  7.       std::call_once(flag,                                                \
  8.                      [&] { *instance = new (std::nothrow) classname();    \
  9.                            std::atexit(CleanUp);});                       \
  10.     }                                                                     \
  11.     return *instance;                                                     \
  12.   }                                                                       \
  13.                                                                           \
  14.   static void CleanUp() {                                                 \
  15.     classname **instance = GetInstancePtrAddr();                          \
  16.     if (*instance != nullptr) {                                           \
  17.       LOGD("CleanUp singleton %s\n", #classname);                         \
  18.       CallShutdown(*instance);                                            \
  19.       delete *instance;                                                   \
  20.       *instance = nullptr;                                                \
  21.     }                                                                     \
  22.   }                                                                       \
  23.                                                                           \
  24. private:                                                                 \
  25.   static classname **GetInstancePtrAddr() {                               \
  26.     static classname *instance = nullptr;                                 \
  27.     return &instance;                                                     \
  28.   }                                                                       \
  29.   classname();                                                            \
  30.   DISALLOW_COPY_AND_ASSIGN(classname)
 楼主| keer_zu 发表于 2022-9-22 15:50 | 显示全部楼层
您需要登录后才可以回帖 登录 | 注册

本版积分规则

1478

主题

12917

帖子

55

粉丝
快速回复 在线客服 返回列表 返回顶部