为什么reinterpret_cast不是constexpr?

问题描述 投票:4回答:1

请考虑以下代码段:

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_cast中的constexpr

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

PROGMEM

在这种情况下,编译器能够证明表达式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中使用?

c++ c++11 avr constexpr reinterpret-cast
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.