我去的文件在从http://www.boost.org/doc/libs/1_47_0/boost/pool/detail/singleton.hpp为什么C++单例实例化需要do_nothing方法?
我的问题:既然create_object是类的静态成员singleton_default它的构造应前主被调用。从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方法,但在此之前主要是停止对象实例化。