a singleton implemention

这样可行是因为以下几点:

1 内部类可以直接访问外部类的静态成员、typedef、枚举值

2 Cleanup对象可能在多线程环境下重复构造初始化, 但无关紧要

#ifndef _CRS_SINGLETON_H_ #define _CRS_SINGLETON_H_ template<class _Type> class Singleton{ public: static _Type *get_instance(); protected: friend class Cleanup; class Cleanup{ public: ~Cleanup(); }; static _Type *instance; static pthread_mutex_t lock; Singleton(){} ~Singleton(){}; }; template<class T> pthread_mutex_t Singleton<T>::lock = PTHREAD_MUTEX_INITIALIZER; template<class T> T *Singleton<T>::instance = NULL; template<class T> Singleton<T>::Cleanup::~Cleanup(){ pthread_mutex_lock(&lock); if(instance){ delete instance; instance = NULL; } pthread_mutex_unlock(&lock); } template<class T> T* Singleton<T>::get_instance(){ static Cleanup _Cleanup; if(!instance){ pthread_mutex_lock(&lock); if(!instance){ instance = new T(); } pthread_mutex_unlock(&lock); } return instance; } #endif /*_CRS_SINGLETON_H_*/

 

 

 

但是和这个实现比较起来, cleanup是不是显得有些多余??

class singleton { public: singleton& instance() { static singleton* refer; if(refer != 0) { guard_lock(mutex); //pseudo code if(refer == 0) { static singleton object; refer = &object; return object; } } return *refer; } };

 

你可能感兴趣的:(a singleton implemention)