我知道C++ 中
的静态初始化顺序失败以及第一次使用惯用语的构造来避免它。因此,在下面的代码中,全局赋值a
可能发生在 of 之前,foo::a
因此值a
未定义。另一方面,全局赋值b
是可以的,因为它调用了函数foo::b()
。
#include <iostream>
#include <string>
using namespace std;
// foo.hpp
class foo {
public:
static const string a;
static const string& b();
static const char* const c;
static const char* const d[2];
static const int e;
static const int f[2];
};
// foo.cpp
const string foo::a("astr");
const string& foo::b() {
static const string t("bstr");
return t;
}
const char* const foo::c = "cstr";
const char* const foo::d[2] = {"dstr1", "dstr2"};
const int foo::e = 5;
const int foo::f[2] = {6, 7};
// main.cpp
// global initializations
string a = foo::a; // dangerous, might be "" or "astr"
string b = foo::b(); // safe, guaranteed to be "bstr"
const char* c = foo::c; // what about these...?
const char* d = foo::d[0];
int e = foo::e;
int f = foo::f[0];
int main() {
cout << a << " " << b << "\n"
<< c << " " << d << "\n"
<< e << " " << f << "\n";
}
(想象一下,我在这里组合了foo.hpp
、foo.cpp
和main.cpp
。)但是作为内置类型或它们的数组的变量呢?因此,此代码中的c
、d
、e
和的全局分配是否安全?f
链接器似乎可以为这些变量设置内存,因此在运行时不需要进行初始化。但是我可以依靠这个吗?
我知道我不应该使用全局变量。但是,我是一个库(foo.cpp 和 foo.hpp)的作者,我无法控制我的库的用户(main.cpp 的作者)做什么。