Home >Backend Development >C++ >How to Force Initialization of Static Members Automatically in C ?
How to Force Initialization of Static Members Automatically
Static members in C are not automatically initialized unless they are used in a way that requires their definition to exist. This behavior can sometimes be inconvenient, especially when you want to perform side effects during static member initialization.
Consider the following example:
<code class="cpp">template<class D> char register_(){ return D::get_dummy(); // static function } template<class D> struct Foo{ static char const dummy; }; template<class D> char const Foo<D>::dummy = register_<D>(); struct Bar : Foo<Bar> { static char const get_dummy() { return 42; } };</code>
In this example, you would expect dummy to be initialized as soon as there is a concrete instantiation of Foo, which you have with Bar. However, this is not the case due to the lazy initialization behavior of static members.
To force the initialization of dummy without any instance of Bar or Foo, you can use one of the following techniques:
<code class="cpp">template<class D> struct Bar : Foo<Bar> { static char const get_dummy() { return (void)dummy; return 42; } };</code>
<code class="cpp">template<typename T, T> struct value { }; template<typename T> struct HasStatics { static int a; // we force this to be initialized typedef value<int&, a> value_user; }; template<typename T> int HasStatics<T>::a = /* whatever side-effect you want */ 0;</code>
<code class="cpp">template<typename T, T> struct var { enum { value }; }; typedef char user; template<typename T> struct HasStatics { static int a; // we force this to be initialized static int b; // and this // hope you like the syntax! user :var<int&, a>::value, :var<int&, b>::value; }; template<typename T> int HasStatics<T>::a = /* whatever side-effect you want */ 0; template<typename T> int HasStatics<T>::b = /* whatever side-effect you want */ 0;</code>
These techniques allow you to force the initialization of static members without requiring user intervention or modifying the derived class. The specific technique to use will depend on your specific requirements and coding style preferences.
The above is the detailed content of How to Force Initialization of Static Members Automatically in C ?. For more information, please follow other related articles on the PHP Chinese website!