gpt4 book ai didi

c++ - 为什么reinterpret_cast不是constexpr?

转载 作者:行者123 更新时间:2023-12-01 23:18:07 24 4
gpt4 key购买 nike

考虑以下代码片段:

static constexpr uint8_t a = 0;
static constexpr const int8_t *b = reinterpret_cast<const int8_t *>(&a);

这无法通过 error: a reinterpret_cast is not a constant expression 进行编译,因为the C++ standard forbids使用reinterpret_castconstexpr .

但是,如果我想将值 b 存储在 PROGMEM 中,编译会成功。 (对于 AVR 微 Controller ):

static constexpr uint8_t a = 0;
static const int8_t PROGMEM *const b = reinterpret_cast<const int8_t *>(&a);

在这种情况下,编译器能够证明表达式 reinterpret_cast<const int8_t *>(&a)是编译时常量,因为它将其结果(指向某个包含零的字节的地址)插入到二进制文件的程序空间中:

_ZL1g:
.zero 1
.section .progmem.data,"a",@progbits
.type _ZL1b, @object
.size _ZL1b, 2
_ZL1b:
.word _ZL1g

另外,我的理解是 reinterpret_cast是一个编译时指令。那么为什么它不能在constexpr内部使用呢? ?

最佳答案

在运行时,C++ 语言具有未定义行为的概念。在某些(明确指定的)条件下,程序具有未定义的行为,这意味着它可以表现出任何行为:它可以崩溃,它可以永远挂起,它可以打印乱码,它可以看起来正常工作,或者它可以做任何事情。其存在原因的一个简单解释是性能。

在运行时这是一种权衡(如果你愿意的话,这是一种妥协),但在编译时这是 Not Acceptable 。如果标准允许在编译时使用 UB,那么不仅在编译程序或无限编译时发生崩溃是合法的,而且您永远无法确定编译后的可执行文件的有效性。

因此,任何形式的 constexpr 都必须 100% 没有未定义行为。对此无一异常(exception)。没有余地。

UB 的一个臭名昭著的来源是reinterpret_castreinterpret_cast 的有效使用非常少,大多数都会导致 UB。另外,实际上不可能检查使用是否有效。所以编译期间不允许使用reinterpret_cast,即constexpr中不允许使用。

关于c++ - 为什么reinterpret_cast不是constexpr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59913275/

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