单例模式 c++实现

目的:为了保证一个类在系统中只有一个实例对象,并且提供一个全局的访问点。

方法:

1、将构造函数私有化,不允许外界访问

2、提供一个getInstance函数作为全局访问点

3、使用双重检查来保证多线程安全

#ifndef SINGLETON_H
#define SINGLETON_H

#include <mutex>

class Singleton
{
public:
    static Singleton* getInstance();
private:
    Singleton();//构造函数私有化,不允许外界创建对象
    static std::mutex mtx;
    static Singleton *instance;
};


#endif // SINGLETON_H
#include "singleton.h"

Singleton* Singleton::instance;
std::mutex Singleton::mtx;


Singleton::Singleton()
{
}

Singleton *Singleton::getInstance()
{
    if(instance == nullptr){
        mtx.lock();
        if(instance == nullptr){
            instance = new Singleton();
        }
        mtx.unlock();
    }
    return instance;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值