【QT】C++线程安全的单例模板
模板代码#pragma once
#include <mutex>
#include <atomic>
// CRTP基类模板 Curiously Recurring Template Parttern—奇异递归模板模式。
template <typename T>
class SingletonCRTP {
public:
// 禁止拷贝构造和赋值操作
SingletonCRTP(const SingletonCRTP&) = delete;
SingletonCRTP& operator=(const SingletonCRTP&) = delete;
// 禁止移动构造和赋值操作
SingletonCRTP(SingletonCRTP&&) = delete;
SingletonCRTP& operator=(SingletonCRTP&&) = delete;
// 获取单例实例
static T* getInstance() {
if (m_instance == nullptr) {
std::unique_lock<std::mutex> lock(m_Mutex); // 加锁
if (m_instance == nullptr) {
T* temp = new (std::nothrow) T();
if (temp == nullptr) {
throw std::bad_alloc();
}
m_instance = temp;
}
}
return m_instance;
}
protected:
SingletonCRTP() = default;
~SingletonCRTP() {
if (m_instance) {
delete m_instance;
m_instance = nullptr;
}
}
// 静态成员变量定义
static T* m_instance;
static std::mutex m_Mutex;
};
// 静态成员变量的模板类特化
template <typename T>
T* SingletonCRTP<T>::m_instance = nullptr;
template <typename T>
std::mutex SingletonCRTP<T>::m_Mutex;
使用方式
#include "SingletonCRTP.h"
class Class1 : public SingletonCRTP<Class1>
{
friend class SingletonCRTP<Class1>;
public:
void DoDoDo() {
printf("Hello World!");
}
}
int main(int argc, char *argv[])
{
Class1::getInstance()->DoDoDo();
}
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]