易失性写入易失性const是否会引入未定义的行为?如果我在写作时放弃挥发怎么办?
volatile const int x = 42; const volatile int *p = &x; *(volatile int *)p = 8; // Does this line introduce undefined behavior? *(int *)p = 16; // And what about this one?
解决方法
当您尝试修改“初始”const对象时,它是未定义的行为(对于两个语句).从C11(N1570)6.7.3 / p6类型限定符(强调我的):
If an attempt is made to modify an object defined with a
const-qualified type through use of an lvalue with non-const-qualified
type,the behavior is undefined.
为了完整性,它可能值得添加,标准也说:
If an attempt is made to refer to an object defined with a
volatile-qualified type through use of an lvalue with
non-volatile-qualified type,the behavior is undefined.
因此后面的陈述,即:
*(int *)p = 16;
对于第二个短语也是未定义的(它是“双UB”).
我相信C的规则是相同的,但不要拥有C 14的副本来确认.