`static const` 与 `const` 的 C++ 语义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3709207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ semantics of `static const` vs `const`
提问by Clifford
In C++ specifically, what are the semantic differences between for example:
具体在 C++ 中,例如之间的语义差异是什么:
static const int x = 0 ;
and
和
const int x = 0 ;
for both static
as a linkage and a storage class specifier (i.e. inside and outside a function).
两者static
作为键和存储类说明(即内部和外部的函数)。
采纳答案by Ben Voigt
At file scope, no difference in C++. const
makes internal linkage the default, and all global variables have static lifetime. But the first variant has the same behavior in C, so that may be a good reason to use it.
在文件范围内,C++ 没有区别。 const
使内部链接成为默认值,并且所有全局变量都有静态生命周期。但是第一个变体在 C 中具有相同的行为,因此这可能是使用它的一个很好的理由。
Within a function, the second version can be computed from parameters. In C or C++ it doesn't have to be a compile-time constant like some other languages require.
在一个函数中,第二个版本可以从参数中计算出来。在 C 或 C++ 中,它不必像其他一些语言所要求的那样是编译时常量。
Within a class, basically the same thing as for functions. An instance const
value can be computed in the ctor-initializer-list. A static const
is set during startup initialization and remains unchanged for the rest of the program. (Note: the code for static
members looks a little different because declaration and initialization are separated.)
在一个类中,基本上与函数相同。const
可以在ctor-initializer-list 中计算实例值。Astatic const
在启动初始化期间设置,并在程序的其余部分保持不变。(注意:static
成员的代码看起来有点不同,因为声明和初始化是分开的。)
Remember, in C++, const
means read-only, not constant. If you have a pointer-to-const
then other parts of the program may change the value while you're not looking. If the variable was defined with const
, then no one can change it after initialization but initialization can still be arbitrarily complex.
请记住,在 C++ 中,const
表示read-only,而不是constant。如果您有一个指向-的指针,const
那么程序的其他部分可能会在您不查看时更改该值。如果变量是用 定义的const
,那么初始化后没有人可以更改它,但初始化仍然可以任意复杂。