换句话来说,什么时候“static const”相当于“#define”? 我搜索了很多,但找不到任何东西。 这与全局初始化依赖关系非常相关(我知道,全局变量是邪恶的,但生活也是邪恶的!)。
我确信该标准不会强制执行,但它可能会提到它。
例如:
static const int a = 2; // Always seen it as compile time
static const int b = 2 * a; // Compile time
static const float c = 3.14; // Compile time
static const float d = c * 1.1 ; // I know the evils of compile time here, but I've seen it both ways (compile and run time)
static const char e = 'p' ; // Compile time
static const int *f = NULL; // Never really tried it :)
最佳答案
这是由 C++11 3.6.2 指定的:执行常量初始化...
if an object with static or thread storage duration is not initialized by a constructor call and if every full-expression that appears in its initializer is a constant expression.
这是你的情况,除了d
:int
和float
没有构造函数,并且初始化器是一个文字,它是一个常量表达式。常量初始化是静态初始化的一部分,并且:
Static initialization shall be performed before any dynamic initialization takes place.
该标准没有明确规定实现,但没有静态初始化的顺序,并且可以理解,初始值本质上是在加载时提供的,并且不会执行任何代码来使这些全局变量具有它们的初始值。
变量d
不满足这些条件,因为它的初始值设定项不是常量表达式(因为c
不是常量表达式)。该标准允许动态或静态初始化 d
。
关于c++ - 标准 (C++) 对编译时初始化有何规定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22414406/