boost的单例源码为there ,我不明白下面源文件中的两个符号:
// ***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++ 中初始化单例?这两个符号是什么意思?
最佳答案
不能。这行代码的作用是:
template<class T>
BOOST_DLLEXPORT T & singleton< T >::instance = singleton< T >::get_instance();
它创建一个静态对象,该对象通过调用 get_instance
进行初始化。由于它是一个类静态对象,因此它在 main 之前初始化。
关于c++ - boost中的单例如何实现在调用main之前初始化所有单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8488108/