#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#include<memory>classSingleton{public:staticSingleton&GetInstance();private:Singleton();~Singleton();// Use auto_ptr to make sure that the allocated memory for instance
// will be released when program exits (after main() ends).
staticstd::auto_ptr<Singleton>s_instance;friendclassstd::auto_ptr<Singleton>;Singleton(constSingleton&);Singleton&operator=(constSingleton&);};#endif
#include"Singleton.h"#include<iostream>#include<boost/thread.hpp>usingnamespacestd;usingnamespaceboost;auto_ptr<Singleton>Singleton::s_instance;Singleton::Singleton(){cout<<"Construct Singleton"<<endl;}Singleton::~Singleton(){cout<<"Destruct Singleton"<<endl;}Singleton&Singleton::GetInstance(){staticmutexs_mutex;if(s_instance.get()==NULL){mutex::scoped_locklock(s_mutex);if(s_instance.get()==NULL){s_instance.reset(newSingleton());}// 'lock' will be destructed now. 's_mutex' will be unlocked.
}return*s_instance;}
#ifndef _ISingleton_H_
#define _ISingleton_H_
#include<memory>#include<boost/thread.hpp>template<typenameT>classISingleton{public:staticT&GetInstance(){staticboost::mutexs_mutex;if(s_instance.get()==NULL){boost::mutex::scoped_locklock(s_mutex);if(s_instance.get()==NULL){s_instance.reset(newT());}// 'lock' will be destructed now. 's_mutex' will be unlocked.
}return*s_instance;}protected:ISingleton(){}~ISingleton(){}// Use auto_ptr to make sure that the allocated memory for instance
// will be released when program exits (after main() ends).
staticstd::auto_ptr<T>s_instance;private:ISingleton(constSingleton&);ISingleton&operator=(constISingleton&);};template<typenameT>std::auto_ptr<T>ISingleton<T>::s_instance;#endif