考虑以下片段:
static constexpr uint8_t a = 0;
static constexpr const int8_t *b = reinterpret_cast<const int8_t *>(&a);
Run Code Online (Sandbox Code Playgroud)
这无法通过 编译error: a reinterpret_cast is not a constant expression,因为C++ 标准禁止使用reinterpret_castin constexpr。
但是,如果我想将值 b 存储在PROGMEM(对于 AVR 微控制器)中,编译会成功:
static constexpr uint8_t a = 0;
static const int8_t PROGMEM *const b = reinterpret_cast<const int8_t *>(&a);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,编译器能够证明该表达式reinterpret_cast<const int8_t *>(&a)是编译时常量,因为它将其结果(指向某个包含零的字节的地址)插入到二进制程序空间中:
_ZL1g:
.zero 1
.section .progmem.data,"a",@progbits
.type _ZL1b, @object
.size _ZL1b, 2
_ZL1b:
.word _ZL1g
Run Code Online (Sandbox Code Playgroud)
另外,我的理解是这reinterpret_cast是一个编译时指令。那么为什么它不能在 a …