问题
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