C++_11——设计模式_单例模式

(是C++专栏第11篇,非C++11标准…)

单例模式

【C++】 ——C++单例模式中的饿汉和懒汉模式

  1. 每个类仅有一个实例,实例被所有程序模块共享
  2. 饿汉模式下,在定义时实例化,在使用之前造成资源浪费
  3. 懒汉模式下,在使用时实例化,需要处理线程安全问题
  4. 应用如,线程池、对话框、日志文件、硬件驱动、注册表…
  5. 注意指针的释放

线程安全的懒汉单例模式(加锁)↓↓↓

// SingeltonModel.h文件
#include <mutex>
#pragma once

// 线程安全类
class SingeltonThread
{
private:
    SingeltonThread() {}
    static std::shared_ptr<SingeltonThread> m_instance;
    static std::mutex m_mutex;
public:
    static SingeltonThread * getInstance()
    {
        if (nullptr == m_instance)
        {
            m_mutex.lock();
            if (nullptr == m_instance)
                m_instance = std::make_shared<SingeltonThread>();
            m_mutex.unlock();
        }
        return m_instance;
    }
};
std::shared_ptr<SingeltonThread> SingeltonThread::m_instance = nullptr;
std::mutex SingeltonThread::m_mutex;

注:

  1. #ifndef与#pragma once
  2. c++中static的作用

Leave a Reply

Your email address will not be published. Required fields are marked *