`static const`vs`const`的C ++语义 [英] C++ semantics of `static const` vs `const`

查看:129
本文介绍了`static const`vs`const`的C ++语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,例如:

static const int x = 0 ;

const int x = 0 ;

存储类说明符(即函数内部和外部)。

for both static as a linkage and a storage class specifier (i.e. inside and outside a function).

推荐答案

在文件范围,C ++没有区别。 const 使内部链接为默认值,所有全局变量都有静态生命周期。但是第一个变体在C中具有相同的行为,因此可能是使用它的一个很好的理由。

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

在类中,基本上与函数相同,可以在 ctor-initializer-list 中计算实例 const 的值。在启动初始化期间设置 static const ,并对程序的其余部分保持不变。 (注意: static 的代码看起来有点不同,因为声明和初始化是分开的。)

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

在C ++中, const 表示只读,而不是常数。如果你有一个指向 - const 的指针,那么程序的其他部分可能会改变你的值。如果变量被定义为 const ,那么没有人能够在初始化之后改变它,但初始化仍然可以是任意复杂的。

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.

这篇关于`static const`vs`const`的C ++语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆