关于 C++ 中的局部和全局静态变量
C++ 入门说
每个局部静态变量在第一次之前初始化执行通过对象的定义.局部静态是函数结束时不会被销毁;它们在编程时被销毁终止.
Each local static variable is initialized before the first time execution passes through the object's definition. Local statics are not destroyed when a function ends; they are destroyed when program terminates.
局部静态变量与全局静态变量有什么不同吗?除了它们被声明的位置,还有什么不同?
void foo () {
static int x = 0;
++x;
cout << x << endl;
}
int main (int argc, char const *argv[]) {
foo(); // 1
foo(); // 2
foo(); // 3
return 0;
}
比较
static int x = 0;
void foo () {
++x;
cout << x << endl;
}
int main (int argc, char const *argv[]) {
foo(); // 1
foo(); // 2
foo(); // 3
return 0;
}
推荐答案
区别在于:
- 名称只能在函数内访问,没有链接.
- 它在第一次执行到达定义时被初始化,不一定在程序的初始化阶段.
第二个区别对于避免静态初始化顺序失败很有用,全局变量可以在初始化之前访问.通过将全局变量替换为返回对局部静态变量的引用的函数,您可以保证它在任何访问它之前已经初始化.(但是,仍然不能保证在任何东西访问它之前它不会被销毁;如果你认为你需要一个全局可访问的变量,你仍然需要非常小心.请参阅 link 可在这种情况下提供帮助.)
The second difference can be useful to avoid the static intialisation order fiasco, where global variables can be accessed before they're initialised. By replacing the global variable with a function that returns a reference to a local static variable, you can guarantee that it's initialised before anything accesses it. (However, there's still no guarantee that it won't be destroyed before anything finishes accessing it; you still need to take great care if you think you need a globally-accessible variable. See the comments for a link to help in that situation.)
相关文章