Singleton.h
#pragma once
#include <utility>
template <typename T>
class Singleton {
public:
template<typename... Args>
static T* Instance(Args&&... args) {
if (instance_ == nullptr) {
instance_ = new T(std::forward<Args>(args)...);
}
return instance_;
}
static void destroyInstance() {
delete instance_;
instance_ = nullptr;
}
private:
static T* instance_;
};
template <class T> T* Singleton<T>::instance_ = nullptr;
example:
#include "Singleton.h"
#include <iostream>
class A{
public:
A(){};
void func() {
std::cout << "hello" << std::endl;
};
};
int main() {
Singleton<A>::Instance()->func();
return 0;
}
console:
hello
本文介绍了一种使用 C++ 实现的通用单例模式,通过模板类 Singleton 提供了线程安全的实例获取和销毁功能。示例代码展示了如何创建 A 类的单例实例并调用其成员函数。
1264

被折叠的 条评论
为什么被折叠?



