Boost中的单例如何实现在调用main之前初始化所有单例?
问题描述:
boost单例的源代码为 有 ,我不理解下面的源文件中的两种符号:
The source code of singleton of boost is there ,I don't understand two notations in the source file below:
// ***include this to provoke instantiation at pre-execution time***
static void use(T const &) {};
BOOST_DLLEXPORT static T & get_instance() {
static detail::singleton_wrapper< T > t;
***// refer to instance, causing it to be instantiated (and
// initialized at startup on working compilers)***
BOOST_ASSERT(! detail::singleton_wrapper< T >::m_is_destroyed);
use(instance);
return static_cast<T &>(t);
}
问题是:这段代码如何在main()之前强制c ++中的单例初始化?这两种表示法是什么意思?
Question is: How could this code force initialization of singleton in c++ before main()?What do these two notation mean?
答
不能.正是这一行:
template<class T>
BOOST_DLLEXPORT T & singleton< T >::instance = singleton< T >::get_instance();
它创建一个静态对象,该对象通过调用get_instance
进行初始化.由于它是一个类静态对象,因此会在main之前进行初始化.
It creates a static object that is initialized by a call to get_instance
. Since it's a class-static object, it's initialized before main.