gpt4 book ai didi

c++ - 标准(C++)对编译时初始化有什么看法?

转载 作者:搜寻专家 更新时间:2023-10-31 01:05:33 24 4
gpt4 key购买 nike

换句话说,“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com