一、前言
boost库的某些组件中虽然有单例模式的实现,但不是很方便单独拿出来使用,于是我在其他人代码的基础上,改动、实现了一个线程安全的、可继承使用的单例模式模板类。编译器会实现局部静态变量的线程安全,因此该单例模式模板类也是线程安全的。程序会在第一次调用单例类的Inst函数的时候初始化单例对象。
二、代码
singleton.hpp
#ifndef SINGLETON_HPP
#define SINGLETON_HPP
template<class T>
class Singleton {
public:
static T& Inst() {
static T instance;
return instance;
}
protected:
Singleton() {};
~Singleton() {};
};
#endif
main.cpp
#include <iostream>
#include "singleton.hpp"
class hello : public Singleton<hello> {
public:
void func(void) {
std::cout << "hello~" << std::endl;
}
};
int main(void) {
hello::Inst().func();
return 0;
}