c++ - 标准 (C++) 对编译时初始化有何规定?

标签 c++ initialization standards

换句话来说,什么时候“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:intfloat没有构造函数,并且初始化器是一个文字,它是一个常量表达式。常量初始化是静态初始化的一部分,并且:

Static initialization shall be performed before any dynamic initialization takes place.

该标准没有明确规定实现,但没有静态初始化的顺序,并且可以理解,初始值本质上是在加载时提供的,并且不会执行任何代码来使这些全局变量具有它们的初始值。

变量d不满足这些条件,因为它的初始值设定项不是常量表达式(因为c不是常量表达式)。该标准允许动态或静态初始化 d

关于c++ - 标准 (C++) 对编译时初始化有何规定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22414406/

相关文章:

c++ - 为什么带有指针子对象的文字类类型的constexpr表达式不能是非类型模板参数

iphone - - 声明时变量的默认值 -

standards - RFC 中对于 HTTP/2 区分大小写的看似矛盾

PHP 群发电子邮件最佳实践? (PHPMailer + Gmail)

c++ - 代码块 libcurl 链接问题 Windows 7

android - 使用 C++ 在 android 中理解和实现 native 绑定(bind)器

c++ - 从文件创建二维 vector ?

java - 为什么计数器没有在上述 for 循环中初始化?

objective-c - NSString 属性和自定义初始化

c++ - SFINAE,演绎与实例化