本文介绍了在C ++中的局部和全局静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ Primer说

局部静态变量与全局静态变量不同吗?

  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;
}


解决方案

p>


  • 此名称只能在函数中访问,并且没有链接。




第二个区别可以用来避免 static intialisation order fiasco ,其中全局变量可以在初始化之前访问。通过用返回对本地静态变量的引用的函数替换全局变量,您可以保证在任何对它进行访问之前对其进行初始化。 (但是,仍然不能保证在访问它之前不会被破坏;如果你认为你需要一个全局可访问的变量,你仍然需要非常小心。参见以帮助解决此问题。)


C++ Primer says

Are local static variables any different from global static variables? Other then the location where they are declared, what else is different?

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;
}

compare with

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;
}
解决方案

The differences are:

  • The name is only accessible within the function, and has no linkage.
  • It is initialised the first time execution reaches the definition, not necessarily during the program's initialisation phases.

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.)

这篇关于在C ++中的局部和全局静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 21:09
查看更多