这是可移植的还是至少安全的使用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