boost::singlton实现的关键有两点
(1) sington 在进入main函数前初始化.(2)第一次使用时, singlton已得到正确的初始化(包括在static code中情况).
boost中的实现代码如下所示:
template <typename T>
struct singleton
{
private:
struct object_creator
{
object_creator() { singleton<T>::instance(); } //初始化create_object时,初始化singleton<T>
inline void do_nothing() const { }
};
static object_creator create_object;
singleton();
public:
typedef T object_type;
static object_type & instance()
{
static object_type obj;
create_object.do_nothing(); //使用create_object,使得编译器一定会初始化create_object
return obj;
}
};
template <typename T> typename singleton<T>::object_creator singleton<T>::create_object;