As far as I know the constructors of global objects need to be called before anybody tries using those objects. However in my program this doesn’t seem to be the case. Here is my simplified code (I compile it with gcc version 4.6.3-1ubuntu5)
#include <iostream>
using namespace std;
struct type_data
{
int id;
type_data()
: id(-1) // set some invalid id
{
cout << "creating a new type data" << endl;
}
};
template <typename T>
struct type_data_for_type
{
static type_data data;
};
template <typename T>
type_data type_data_for_type<T>::data;
struct type_registry
{
static type_registry& instance()
{
static type_registry i;
return i;
}
void register_type(type_data& t)
{
cout << "registering a type" << endl;
t.id = last_id++;
}
int last_id;
};
template <typename T>
struct registrator
{
registrator()
{
type_registry::instance().
register_type(type_data_for_type<T>::data);
}
int unused;
static registrator payload;
};
template <typename T>
registrator<T> registrator<T>::payload;
class foo {};
inline void register_foo()
{
registrator<foo>::payload.unused = 1;
}
int main()
{
cout << type_registry::instance().last_id << endl;
cout << type_data_for_type<foo>::data.id << endl;
return 0;
}
Basically it registers the type foo globally via register_foo. I expect the output to be:
creating a new type data
registering a type
1
0
But instead it is:
registering a type
creating a new type data
1
-1
This means that i’ve set the id of a type_data object before its constructor was called.
So, is this a compiler bug? Am I missing something? Can I make this work?
I believe you cannot rely on the order of initialization of static member variables of class templates in this case.
Relevant here is § 3.6.2/2 of the C++ Standard:
*”Dynamic initialization of a non-local variable with static storage duration is either ordered or
unordered. Definitions of explicitly specialized class template static data members have ordered initialization. Other class template static data members (i.e., implicitly or explicitly instantiated specializations) *have unordered initialization.”
And of course also § 9.4.2/6, which refers the above rule:
“Static data members are initialized and destroyed exactly like non-local variables (3.6.2, 3.6.3).”