C++单例模式:
//singleton.h
template<typename T>
class Singleton : noncopyable
{
public:
static T& Instance()
{
pthread_once(&ponce_, &Singleton::init);
return *value_;
}
private:
Singleton();
~Singleton();
static void init()
{
value_ = new T();
}
private:
static pthread_once ponce_;
static T* value_;
};
//注意:必须头文件中定义static变量
template <typename T>
pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT;
template<typename T>
T* Singleton<T>::value_ = NULL;
使用方法:
MyClass& mc = Singleton<MyClass>::Instance();
noncopyable基类实现地址:https://blog.csdn.net/xu215740578/article/details/97388859
本文源码学习自muduo