【发布时间】:2014-11-02 16:19:10
【问题描述】:
我正在查看来自 http://www.boost.org/doc/libs/1_47_0/boost/pool/detail/singleton.hpp 的文档
我的问题:因为 create_object 是类 singleton_default 的静态成员,所以它的构造函数应该在 main 之前调用。从 object_creator 的构造函数中,调用了 singleton_default::instance,这确保了 obj 在 main 之前被实例化。我不遵循的是 do_nothing 方法的需要。文档提到它强制实例化 create_object 但不是应该在 main 启动之前初始化类的静态成员吗?通过这个令牌, singleton_default::create_object 实例化是否不够好?
这是代码
// T must be: no-throw default constructible and no-throw destructible
template <typename T>
struct singleton_default
{
private:
struct object_creator
{
// This constructor does nothing more than ensure that instance()
// is called before main() begins, thus creating the static
// T object before multithreading race issues can come up.
object_creator() { singleton_default<T>::instance(); }
inline void do_nothing() const { }
};
static object_creator create_object;
singleton_default();
public:
typedef T object_type;
// If, at any point (in user code), singleton_default<T>::instance()
// is called, then the following function is instantiated.
static object_type & instance()
{
// This is the object that we return a reference to.
// It is guaranteed to be created before main() begins because of
// the next line.
static object_type obj;
// The following line does nothing else than force the instantiation
// of singleton_default<T>::create_object, whose constructor is
// called before main() begins.
create_object.do_nothing();
return obj;
}
};
template <typename T>
typename singleton_default<T>::object_creator
singleton_default<T>::create_object;
我尝试删除 do_nothing 方法,但这会在 main 之前停止对象实例化。
【问题讨论】:
标签: c++ design-patterns boost