Possible Duplicate:
(static initialization/template instantiation) problems with factory pattern
trying to force static object initialization
https://stackoverflow.com/a/2852234/673730
Assume the following class:
template<class X>
struct A
{
static bool x;
static bool foo()
{
cout << "here";
return true;
}
};
template<class X>
bool A<X>::x = A<X>::foo();
I would have assumed that when I specialize A
, the static field x
would get initialized. However, the following:
A<int> a;
//no output
doesn't result in a call to foo
. If I try to access the member, the behavior is as expected:
A<int> a;
bool b = a.x;
//output: here
EDIT: How can I make sure A::x
is initialized without accessing it?
When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name. Static variables are initialized only once.
A static variable in a block is initialized only one time, prior to program execution, whereas an auto variable that has an initializer is initialized every time it comes into existence. A static object of class type will use the default constructor if you do not initialize it.
We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.
If the initial value of a static variable can't be evaluated at compile time, the compiler will perform zero-initialization. Hence, during static initialization all static variables are either const-initialized or zero-initialized. After static initialization, dynamic initialization takes place.
If a template is implicitly specialised by virtue of being instantiated, then only those members that are actually referred to are instantiated.
Contrast this with explicit class template instantiation (template struct A<int>;
), which instantiates and creates code for all members. (You can also instantiate only specific members individually: template bool A<int>::x;
.)
This think is the reference(14.7.1.2) :
Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.
template<class X, bool y>
struct A
{
static cosnt bool x = y;
static bool foo()
{
cout << "here";
return true;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With