我去的文件在從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方法,但在此之前主要是停止對象實例化。