gcc是否有关于静态成员初始化时间的任何保证,尤其是关于模板类?
我想知道是否可以确保在跨多个编译单元实例化类时,静态成员(PWrap_T<T>::p_s
)将在main()
之前初始化。在main开始时尝试从每个编译单元中手动触摸符号是不切实际的,但是我不清楚其他任何方法都可以使用。
我已经使用不同单位的bar()
这样的方法进行了测试,并且始终都能获得理想的结果,但是我需要知道gcc何时/是否会抽出地毯以及它是否可以预防。
此外,在库完成加载之前,是否将初始化DSO中的所有静态成员?
#include <iostream>
#include <deque>
struct P;
inline std::deque<P *> &ps() { static std::deque<P *> d; return d; }
void dump();
struct P {
P(int id, char const *i) : id_(id), inf_(i) { ps().push_back(this); }
void doStuff() { std::cout << id_ << " (" << inf_ << ")" << std::endl; }
int const id_;
char const *const inf_;
};
template <class T>
struct PWrap_T { static P p_s; };
// *** Can I guarantee this is done before main()? ***
template <class T>
P PWrap_T<T>::p_s(T::id(), T::desc());
#define PP(ID, DESC, NAME) /* semicolon must follow! */ \
struct ppdef_##NAME { \
constexpr static int id() { return ID; } \
constexpr static char const *desc() { return DESC; } \
}; \
PWrap_T<ppdef_##NAME> const NAME
// In a compilation unit apart from the template/macro header.
void dump() {
std::cout << "[";
for (P *pp : ps()) { std::cout << " " << pp->id_ << ":" << pp->inf_; }
std::cout << " ]" << std::endl;
}
// In some compilation unit.
void bar(int cnt) {
for (int i = 0; i < cnt; ++i) {
PP(2, "description", pp);
pp.p_s.doStuff();
}
}
int main() {
dump();
PP(3, "another", pp2);
bar(5);
pp2.p_s.doStuff();
}
另外,尝试使用
__attribute__ ((init_priority(int)))
或__attribute__ ((constructor))
进行模板成员的初始化会产生warning: attributes after parenthesized initializer ignored
,而且我不知道有关静态初始化的其他技巧。在此先感谢任何可以给我答案的人!
最佳答案
该标准保证在从外部源使用与您的对象相同的转换单元中的任何函数/变量之前,都要初始化静态存储持续时间对象。
这里的措词旨在与共享库一起使用。因为可以在main()启动之后动态加载共享库,所以语言规范必须足够灵活以应付它。但是,只要您从翻译单元外部访问对象,就可以确保在获得访问权限之前就已经构造了该对象(除非您进行了病理操作)。
但是,如果在同一编译单元中另一个静态存储持续时间对象的构造函数中使用了它,则不会停止在初始化之前使用它。
但是您可以通过以下技术轻松地手动提供保证,以确保在使用之前正确初始化了静态对象。
只需将静态变量更改为静态函数即可。然后在函数内部声明一个返回的静态成员。因此,您可以像以前一样使用它(只需添加()
)。
template <class T>
struct PWrap_T
{
static P& p_s(); // change static variable to static member function.
// Rather than the type being P make it a reference to P
// because the object will be held internally to the function
};
template <class T>
P& PWrap_T<T>::p_s()
{
// Notice the member is static.
// This means it will live longer than the function.
// Also it will be initialized on first use.
// and destructed when other static storage duration objects are destroyed.
static P p_s_item(T::id(), T::desc());
return p_s_item;
// Note its not guaranteed to be created before main().
// But it is guaranteed to be created before first use.
}
因此,在这里您可以获得全局(无论它们是什么)的好处。您将获得有保证的构造/破坏,并且知道可以正确使用该对象。
您需要进行的唯一更改是:
void bar(int cnt) {
for (int i = 0; i < cnt; ++i) {
PP(2, "description", pp);
pp.p_s().doStuff();
// ^^ Add the braces here.
}
}
关于c++ - gcc中模板的非延迟静态成员初始化?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20601358/