Coffee_Candy

90 分类: Qt软件开发,C++boost后端

C++11后的线程安全单例模式创建

C++11之后引入了std::call_once,并且static也保证了线程安全所以可以组合来创建线程安全的单例类
C++单例代码
#include <functional>
#include <iostream>
#include <memory>
#include <mutex>
template <typename T>
class Singleton
{
protected:
    //拷贝构造,赋值构造全部delete
    //默认构造
    Singleton() = default;
    Singleton& operator = (const Singleton<T> & st) = delete;
    Singleton(const Singleton<T>&) = delete;
    //存储模板T的实例
    static std::shared_ptr<T> _instance;
public:
    static std::shared_ptr<T> GetInstance()
    {
            //判断是否第一次调用
        static std::once_flag s_flag;
        std::call_once(s_flag, [&]() {
                    //第一次调用就new出来
            _instance = std::shared_ptr<T>(new T);
        });
        return _instance;
    }


    ~Singleton()
    {
        std::cout << "this is singleton delete" << std::endl;
    }
};

template <typename T>
//告知编译器你的要修改的单例类的属性的类型,哪个单例类里的哪个东西=nullptr
std::shared_ptr<T> Singleton<T>::_instance= nullptr;
//保证模板类的static变量类型一致,同时保证static只有一个,所以在h中初始化,


继承的演示(主要看public Singleton这个位置)
在继承的时候告知编译器模板类的类型是什么
    class HttpMgr:public QObject,public Singleton<HttpMgr>,public std::enable_shared_from_this<HttpMgr>
{
    Q_OBJECT
public:
    ~HttpMgr();
    void PostHttpReq(QUrl url,QJsonObject json,ReqId req_id,Modules mod);
private:
    friend class Singleton<HttpMgr>;
    HttpMgr();
    QNetworkAccessManager _manager;
private slots:
    void slot_http_finish(ReqId id, QString res, ErrorCodes err, Modules mod);
signals:
    void sig_http_finish(ReqId id,QString res,ErrorCodes err,Modules mod);
    void sig_reg_mod_finish(ReqId id, QString res, ErrorCodes err);
    void sig_reset_mod_finish(ReqId id, QString res, ErrorCodes err);
};

2024-10-16T03:30:43.png

#none

作者: Coffee_Candy

版权: 除特别声明,均采用BY-NC-SA 4.0许可协议,转载请表明出处

目录Content

评论已关闭