How singleton in boost implement all singletons are initialized before main is called?

橙三吉。 提交于 2019-12-10 10:51:30

问题


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);
}

Question is: How could this code force initialization of singleton in c++ before main()?What do these two notation mean?


回答1:


It can't. It's this line that does:

template<class T>
BOOST_DLLEXPORT T & singleton< T >::instance = singleton< T >::get_instance();

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.




回答2:


I think the first comment actually refers to the line above,

BOOST_DLLEXPORT static T & instance;

which constructs a static instance of T. Statics are initialized before main is started, that's just a C++ rule.




回答3:


You're just showing part of the code, which may explain why you don't understand.

Before a program is executed, it must first be loaded into memory. At that time, if a static or global scope variable is found, it is initialized with either the value specified or the default compiler.

Then if you specify a static instance of class, it's constructor will be called even before main! That what boost uses to provide this functionality.



来源:https://stackoverflow.com/questions/8488108/how-singleton-in-boost-implement-all-singletons-are-initialized-before-main-is-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!