c++ - boost中的单例如何实现在调用main之前初始化所有单例?

标签 c++ boost singleton

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/

相关文章:

c++ - 为什么我的仿函数成员变量 "reset"? (c++)

C++ ifstream 对象 "reseting"

c++ - 如何在Windows和Linux上用C++读取系统信息?

c++ - 创建行优先数组时出现段错误

单例类与具有静态成员的类

Typescript 类 - 私有(private)字段应该在构造函数中吗?

c++ - boost::bind 与映射,绑定(bind) std::pair 和 std::map::value_type 有什么区别?

c++ - mutex lock fail with invalid argument 是什么意思?

c++ - boost asio : unable to acknowledge a file transfer

php - 通过Ajax调用PHP文件中的MySQL连接单例对象