考虑以下片段:
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
, 因为C++标准禁止 http://eel.is/c++draft/expr.const using reinterpret_cast
in constexpr
.
但是,如果我想将值 b 存储在中,编译会成功PROGMEM https://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html(对于 AVR 微控制器):
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++ 语言有未定义行为的概念。在某些(明确指定的)条件下,程序具有未定义的行为,这意味着它可以表现出任何行为:它可以崩溃,它可以永远挂起,它可以打印乱码,它可以看起来正常工作,或者它可以做任何事情。其存在原因的一个简单解释是性能。
在运行时这是一种权衡(如果你愿意的话,这是一种妥协),但在编译时这是不可接受的。如果标准允许在编译时使用 UB,那么不仅在编译程序或无限编译时发生崩溃是合法的,而且您永远无法确定编译后的可执行文件的有效性。
因此,任何形式的constexpr
必须 100% 没有未定义的行为。对此无一例外。没有余地。
UB 的一个臭名昭著的来源是reinterpret_cast
。有效用途很少reinterpret_cast
,其中大多数导致 UB。另外,实际上不可能检查使用是否有效。所以reinterpret_cast
编译期间不允许,即 constexpr 中不允许。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)