c++宏编写单例模式的3种写法

饿汉:一开始就实例化对象
懒汉:调用(需要)才去实例化对象

写法一,可用于懒汉和饿汉

线程安全
singleton.h

#ifndef SINGLETON_H
#define SINGLETON_H

#include <mutex>

#define DECLARESINGLETON(class_name) \
private: \
    static class_name *_instance; \
public: \
static class_name *instance() \
{ \
    static std::mutex mutex; \
    if(!_instance) \
    { \
        std::lock_guard<std::mutex> lock(mutex); \
        if(!_instance) \
        { \
            _instance = new class_name; \
        } \
    } \
    return _instance; \
} \
private: \
    class_name(){} \

#endif // SINGLETON_H

写法二 利用c++11

利用c++11静态局部变量,底层双检查机制实现线程安全。
mysingleton.h

#ifndef MYSINGLETON_H
#define MYSINGLETON_H

#endif // MYSINGLETON_H

#define MYDECLARESINGLETON(class_name) \
private: \
    class_name(){} \
public: \
    static class_name *instance() \
    { \
        static class_name _instance;\
        return &_instance; \
    } \

写法三,无c++11

mysingleton.h

#ifndef SINGLETON_H
#define SINGLETON_H

#include <mutex>

#define DECLARESINGLETON(class_name) \
public: \
static class_name *instance() \
{ \
	static class_name *_instance = nullptr \
    static std::mutex mutex; \
    if(!_instance) \
    { \
        std::lock_guard<std::mutex> lock(mutex); \
        if(!_instance) \
        { \
            _instance = new class_name; \
        } \
    } \
    return _instance; \
} \
private: \
    class_name(){} \

#endif // SINGLETON_H

调用

test1.h

#ifndef TEST1_H
#define TEST1_H

#include "singleton.h"

class test1
{
    DECLARESINGLETON(test1)
    public:
        int add(int,int);
};

#endif // TEST1_H

test1.cpp

#include "test1.h"
#include <iostream>

//test1* test1::_instance = nullptr; // 写法一使用时去掉注释,懒汉
//test1* test1::_instance = new  test1; // 写法一使用时去掉注释,饿汉

int test1::add(int a,int b)
{
    test1 *p = test1::instance();
    std::cout << p << std::endl;
    return a+b;

mian.cpp

#include <iostream>
#include "test1.h"

using namespace std;

int main()
{
    test1 *p1 = test1::instance();
    test1 *p2 = test1::instance();
    cout << p1 << endl;
    cout << p2 << endl;
    return 0;
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值