【发布时间】:2011-06-11 03:29:08
【问题描述】:
当变量位于 .cpp 文件的全局范围内而不是函数中时,将其标记为 static 是否有用?
你也可以对函数使用 static 关键字吗?如果是,它们的用途是什么?
【问题讨论】:
-
听起来好像有人叫任何作业
标签: c++ static global-variables global static-variables
当变量位于 .cpp 文件的全局范围内而不是函数中时,将其标记为 static 是否有用?
你也可以对函数使用 static 关键字吗?如果是,它们的用途是什么?
【问题讨论】:
标签: c++ static global-variables global static-variables
在这种情况下,关键字 static 意味着函数或变量只能由同一 cpp 文件中的代码使用。关联的符号不会被导出,也不会被其他模块使用。
当您知道其他模块不需要您的全局函数或变量时,这是避免在大型软件中发生名称冲突的好习惯。
【讨论】:
是的,如果你想声明文件范围变量,那么static 关键字是必须的。 static 在一个翻译单元中声明的变量不能被另一个翻译单元引用。
顺便说一句,在 C++03 中不推荐使用 static 关键字。
C++ 标准 (2003) 中的 $7.3.1.1/2 部分内容如下:
static关键字的使用是 在 a 中声明对象时不推荐使用 命名空间范围;这 unnamed-namespace 提供了一个优越的 替代。
C++ 更喜欢 unnamed 命名空间而不是 static 关键字。请参阅此主题:
【讨论】:
举个例子-
// At global scope
int globalVar; // Equivalent to static int globalVar;
// They share the same scope
// Static variables are guaranteed to be initialized to zero even though
// you don't explicitly initialize them.
// At function/local scope
void foo()
{
static int staticVar ; // staticVar retains it's value during various function
// function calls to foo();
}
它们都只有在程序终止/退出时才停止存在。
【讨论】: