Qt实现线程安全的单例模式

实现方式

1、实现单例
把类的构造函数、拷贝构造函数、赋值操作符定义为private的;
把获取单例的接口和唯一的实例指针定义为static的,不需要实例化,直接通过类名即可访问。
2、支持多线程
采用双重校验法,在获取单例的函数中使用互斥锁,确保不会出现两个线程同时new出这个单例类的实例化。
3、解决内存泄漏
析构单例指针,单独写一个类,利用这个类的析构函数来析构单例指针。

代码实现

Instance.h

#ifndef INSTANCE_H
#define INSTANCE_H

#include <QObject>
#include <QMutex>
#include <QDebug>

class Instance : public QObject
{
    Q_OBJECT
public:
    static Instance *getInstance()
    {
        if(m_pInstance == NULL)
        {
            QMutexLocker mlocker(&m_mutex);
            if(m_pInstance == NULL)
            {
                m_pInstance = new Instance();
            }
        }
        return m_pInstance;
    }
    void debugStr();//对外接口,实现功能
    QString m_str;//对外接口,实现功能
private:
    explicit Instance(QObject *parent = 0);//构造函数
    Instance(const Instance &,QObject *parent = 0): QObject(parent) {}//拷贝构造函数
    Instance& operator =(const Instance&){return *this;}//赋值操作符重写
    static Instance* m_pInstance;//定义单例指针
    static QMutex m_mutex;//互斥锁

public:
    class Garbo     //专门用来析构m_pInstance指针的类
    {
    public:
        ~Garbo()
        {
            if(m_pInstance != NULL)
            {
                delete m_pInstance;
                m_pInstance = NULL;
                qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"m_pInstance 被析构";
            }
        }
    };
    static Garbo m_garbo;
};
#endif // INSTANCE_H

Instance.cpp

#include "instance.h"
#include <QDebug>

Instance* Instance::m_pInstance = NULL;
Instance::Garbo m_Garbo;
QMutex Instance::m_mutex;
void Instance::debugStr()
{
    qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"debugStr ";
}

Instance::Instance(QObject *parent) : QObject(parent)
{
    m_str = "hello World!";
}

调用单例

包含头文件,通过单例入口调用函数或变量。
#include “instance.h”
Instance::getInstance()->debugStr();
Instance::getInstance()->m_str;

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值