模板代码
#pragma once
#include <mutex>
#include <atomic>
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();
}