打印

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

[复制链接]
261|1
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
keer_zu|  楼主 | 2022-9-15 14:14 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
C++, ST, AN, ce, TI, ic
#define DECLARE_SINGLETON(classname)                                      \
public:                                                                  \
  static classname *Instance(bool create_if_needed = true) {              \
    classname **instance = GetInstancePtrAddr();                          \
    if (!*instance && create_if_needed) {                                 \
      static std::once_flag flag;                                         \
      std::call_once(flag,                                                \
                     [&] { *instance = new (std::nothrow) classname();    \
                           std::atexit(CleanUp);});                       \
    }                                                                     \
    return *instance;                                                     \
  }                                                                       \
                                                                          \
  static void CleanUp() {                                                 \
    classname **instance = GetInstancePtrAddr();                          \
    if (*instance != nullptr) {                                           \
      LOGD("CleanUp singleton %s\n", #classname);                         \
      CallShutdown(*instance);                                            \
      delete *instance;                                                   \
      *instance = nullptr;                                                \
    }                                                                     \
  }                                                                       \
                                                                          \
private:                                                                 \
  static classname **GetInstancePtrAddr() {                               \
    static classname *instance = nullptr;                                 \
    return &instance;                                                     \
  }                                                                       \
  classname();                                                            \
  DISALLOW_COPY_AND_ASSIGN(classname)

使用特权

评论回复

相关帖子

沙发
keer_zu|  楼主 | 2022-9-22 15:50 | 只看该作者
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

1314

主题

12271

帖子

53

粉丝