據我所知,在任何人嘗試使用這些對象之前,需要調用全局對象的構造函數。但是在我的程序中,這似乎並不是這樣。這是我的簡化的代碼首次使用對象後調用的全局對象構造函數
#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;
}
基本上它經由register_foo全局寄存器的類型FOO(I用gcc版本4.6.3-1ubuntu5編譯它)。我希望可以將輸出爲:
creating a new type data
registering a type
1
0
但取而代之的則是:
registering a type
creating a new type data
1
-1
這意味着,我給自己定一個type_data
對象的ID它的構造函數被調用之前。
那麼,這是一個編譯器錯誤?我錯過了什麼嗎?我可以做這個工作嗎?
我相信你不能依賴於構造全局對象的相對順序 –
相關:http://www.parashift.com/c++-faq/static-init-order.html [10.14]什麼是「靜態初始化順序悲劇「? – Patashu