Singleton类图
数据成员:
static pthread_once_t ponce_:一个pthread_once_t类型的ponce_对象,ponce_保证一个函数只被执行一次
static T* value_:一个类型为T的指针
成员函数:
static T& instance():返回单例对象*value_
Singleton():构造函数
~Singleton():析构函数
static void init():创建T类型对象value_,并注册销毁函数destroy()
static void destroy():销毁T类型对象value_
Singleton.h
//Singleton模板类,保证单例类的线程安全
#ifndef MUDUO_BASE_SINGLETON_H
#define MUDUO_BASE_SINGLETON_H
#include <boost/noncopyable.hpp>
#include <pthread.h>
#include <stdlib.h> // atexit
namespace muduo
{
template<typename T>
class Singleton : boost::noncopyable
{
public:
//返回单例对象*value_
static T& instance()
{
//pthread_once保证init在本线程中只被执行一次
//即保证value_对象只被创建一次,保证value_对象是单例的,保证线程安全
pthread_once(&ponce_, &Singleton::init);
return *value_;
}
private:
Singleton();
~Singleton();
//创建T类型对象value_
static void init()
{
value_ = new T();
//注册销毁函数destroy,当程序正常终止时,调用销毁函数destroy
::atexit(destroy);
}
//销毁T类型对象value_
static void destroy()
{
//要销毁的对象value_的类型T必须是一个complete_type
typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];
delete value_;
}
private:
//一个pthread_once_t类型的ponce_对象,ponce_保证一个函数只被执行一次
static pthread_once_t ponce_;
//一个类型为T的指针
static T* value_;
};
template<typename T>
pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT;
template<typename T>
T* Singleton<T>::value_ = NULL;
}
#endif