现在的位置: 首页 > 综合 > 正文

boost singleton

2013年10月11日 ⁄ 综合 ⁄ 共 816字 ⁄ 字号 评论关闭

研究了一下, boost里其实有两种singleton, 还有一种冒似更简单, 精简如下 

# pragma once

template <class T>
class boost_singleton
{
private:
	__declspec(dllexport) static T & _object;
	static void use(T const &) {}
public:
	 static T & instance() {
		static T t;
		use(_object);
		return t;
	}

};

template<class T>
__declspec(dllexport) T & boost_singleton< T >::_object = boost_singleton< T >::instance();

 

//////////////////////////////////////////////////////////////////////////
//
 template <typename T>
 class boost_singleton_default
 {
 private:
 	struct object_creator
 	{
 		object_creator() 
 		{
 			boost_singleton_default<T>::instance(); 
 		}
 		inline void do_nothing() const {}
 	};
 
 	static object_creator create_object_;
 public:
 	static T &instance()
 	{
 		static T obj;
 		create_object_.do_nothing(); 
 		return obj;
 	}
 };
 //因为create_object_是类的静态变量,必须有一个通用的声明
 template <class T>  
 typename boost_singleton_default<T>::object_creator boost_singleton_default<T>::create_object_;
 

【上篇】
【下篇】

抱歉!评论已关闭.