Qt implements thread-safe singleton mode

Method to realize

1. Realize the singleton.
Define the class constructor, copy constructor, and assignment operator as private;
define the singleton interface and the unique instance pointer as static, no need to instantiate, just pass the class name directly access.
2. Support for multi-threading.
The double check method is used to use mutual exclusion locks in the function of obtaining the singleton to ensure that no two threads will simultaneously new the instantiation of this singleton class.
3. Solve memory leaks
Deconstruct the singleton pointer, write a class separately, and use the destructor of this class to deconstruct the singleton pointer.

Code

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!";
}

Call singleton

Contains the header file, and calls functions or variables through the singleton entry.
#include “instance.h”
Instance::getInstance()->debugStr();
Instance::getInstance()->m_str;

Guess you like

Origin blog.csdn.net/weixin_40355471/article/details/110426528