一种通过宏定义在class内部实现单例模式的方法

[复制链接]
 楼主| keer_zu 发表于 2023-4-14 10:52 | 显示全部楼层 |阅读模式

  1. #define DISALLOW_COPY_AND_ASSIGN(classname) \
  2.   classname(const classname &) = delete;    \
  3.   classname &operator=(const classname &) = delete;

  4. #define DECLARE_SINGLETON(classname)                                      \
  5. public:                                                                  \
  6.   static classname *Instance(bool create_if_needed = true) {              \
  7.     classname **instance = GetInstancePtrAddr();                          \
  8.     if (!*instance && create_if_needed) {                                 \
  9.       static std::once_flag flag;                                         \
  10.       std::call_once(flag,                                                \
  11.                      [&] { *instance = new (std::nothrow) classname();    \
  12.                            std::atexit(CleanUp);});                       \
  13.     }                                                                     \
  14.     return *instance;                                                     \
  15.   }                                                                       \
  16.                                                                           \
  17.   static void CleanUp() {                                                 \
  18.     classname **instance = GetInstancePtrAddr();                          \
  19.     if (*instance != nullptr) {                                           \
  20.       LOGD("CleanUp singleton %s\n", #classname);                         \
  21.       CallShutdown(*instance);                                            \
  22.       delete *instance;                                                   \
  23.       *instance = nullptr;                                                \
  24.     }                                                                     \
  25.   }                                                                       \
  26.                                                                           \
  27. private:                                                                 \
  28.   static classname **GetInstancePtrAddr() {                               \
  29.     static classname *instance = nullptr;                                 \
  30.     return &instance;                                                     \
  31.   }                                                                       \
  32.   classname();                                                            \
  33.   DISALLOW_COPY_AND_ASSIGN(classname)
您需要登录后才可以回帖 登录 | 注册

本版积分规则

1478

主题

12912

帖子

55

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

1478

主题

12912

帖子

55

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