单例宏常用实现

共享指针 ,因为要在外外部创建,构造函数必须是pulic

#define DECLARE_SINGLETON(classname)                                       \
 public:                                                                   \
  static classname *instance() {                                           \
    static std::shared_ptr<classname> instance_cached = nullptr;           \
    if (instance_cached == nullptr) {                                      \
      static std::once_flag flag;                                          \
      std::call_once(                                                      \
          flag, [&] { instance_cached = std::make_shared<classname>(); }); \
    }                                                                      \
    return instance_cached.get();                                          \
  }                                                                        \
                                                                           \
 private:

常规

#pragma once

/*
 * @brief   :定义单例类宏
 */


#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; \
        static std::mutex s_mutex;

#define SINGLETON_IMPL(Class) \
    Class* Class::s_pInstance = NULL; \
    std::mutex Class::s_mutex; \
    Class* Class::instance() { \
        if (s_pInstance == NULL) { \
            s_mutex.lock(); \
            if (s_pInstance == NULL) { \
                s_pInstance = new Class; \
            } \
            s_mutex.unlock(); \
        } \
        return s_pInstance; \
    } \
    void Class::exitInstance() { \
        s_mutex.lock(); \
        if (s_pInstance) {  \
            delete s_pInstance; \
            s_pInstance = NULL; \
        }   \
        s_mutex.unlock(); \
    }

头文件:SINGLETON_DECL(Aclass)

实现文件:SINGLETON_IMPL(Aclass)

通用模板 

template<class T>
class Singleton
{
public:
    static T& instance(){
        static T theInstance;
        return theInstance;
    }

protected:
    Singleton(){}
    virtual ~Singleton(){}

private:
//    Singleton(const Singleton&);
//    Singleton& operator =(const Singleton&);

};

//单例类
class MyClass : public Singleton<MyClass>
{
public:
    void setValue(int n){x = n;}
    int getValue(){return x;}

protected:
    friend class Singleton<MyClass>;
    MyClass(){x = 0;}

private:
    ~MyClass();
    int x;
};

int main()
{
    MyClass& m = MyClass::instance();
    cout << m.getValue() << endl;
    m.setValue(1);
    cout << m.getValue() << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值