這是可移植的還是至少安全的使用g ++?全局變量的C++初始化順序
#include <iostream>
#include <vector>
struct c {};
std::vector<c*> v;
struct i : c { i() { v.push_back (this); } } a, b, c;
int main() {
std::cout << v.size() << "\n"; // outputs 3 with g++
}
編輯:
好吧,我需要的原來是有點困難:與模板相同的代碼:
#include <iostream>
#include <vector>
template < typename T > struct c {};
template < typename T > struct cv { static std::vector<c<T>*> v; };
template < typename T > std::vector<c<T>*> cv<T>::v;
template < typename T > struct i : c<T> { i() { cv<T>::v.push_back (this); } };
cv<int> dummy; // even this won't initialize cv<int>::v
i<int> a, b, d;
int main() {
std::cout << cv<int>::v.size() << "\n"; // outputs 0 :-(
}
我怎麼能解決這個問題,以按上述方式工作?
編輯2:
這裏是一個醜陋的修復與宏(我希望有一個更好的方式來做到這一點):
#include <iostream>
#include <vector>
template < typename T > struct c {};
template < typename T > struct cv;
#define INITCV(X) \
struct v##X { static std::vector<c<X>*> v; }; \
std::vector<c<X>*> v##X::v; \
template <> struct cv<X> { typedef v##X V; }
template < typename T > struct i : c<T> { i() { cv<T>::V::v.push_back (this); } };
INITCV(int);
i<int> a, b, d;
int main() {
std::cout << cv<int>::V::v.size() << "\n"; // outputs 3 again :-)
}
(順便說一句,我應該已經發布了一個新問題而不是編輯?)
謝謝你在規範中查找。不幸的是,這似乎並不適用於模板,就像我修改過的問題一樣。 – Thomas 2010-08-18 18:42:17