C++单例模式类
直观易懂
#include <iostream>
template <typename T>
class Singleton {
public:
static T* GetInstence() {
static T * instence = NULL;
if(instence == NULL) {
instence = new T();
}
return instence;
}
protected:
Singleton() = delete;
Singleton(const Singleton<T> &) = delete;
Singleton<T> & operator = (const Singleton<T> &) = delete;
};
class A {
public:
A() {
std::cout << "this is A" << std::endl;
}
};
class B {
public:
B() {
std::cout << "this is B" << std::endl;
}
};
int main() {
A *a = Singleton<A>::GetInstence();
B *b = Singleton<B>::GetInstence();
delete a;
delete b;
return 0;
}
C++模板实现的单例模式
这篇博客介绍了如何使用C++模板实现单例模式,展示了如何创建和使用A和B两个类的单例实例。代码中定义了一个泛型Singleton模板类,用于确保类A和B的唯一实例化,避免了多线程环境中可能的并发问题。
12万+

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



