(是C++专栏第11篇,非C++11标准…)
单例模式
- 每个类仅有一个实例,实例被所有程序模块共享
- 饿汉模式下,在定义时实例化,在使用之前造成资源浪费
- 懒汉模式下,在使用时实例化,需要处理线程安全问题
- 应用如,线程池、对话框、日志文件、硬件驱动、注册表…
- 注意指针的释放
线程安全的懒汉单例模式(加锁)↓↓↓
// 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;
注: