boost singleton

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

# pragma once

template 
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
__declspec(dllexport) T & boost_singleton< T >::_object = boost_singleton< T >::instance();





 

//////////////////////////////////////////////////////////////////////////
//
 template 
 class boost_singleton_default
 {
 private:
 	struct object_creator
 	{
 		object_creator() 
 		{
 			boost_singleton_default::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   
 typename boost_singleton_default::object_creator boost_singleton_default::create_object_;
 



你可能感兴趣的:(boost singleton)