volatile 写入 volatile const 会引入未定义的行为吗?如果我写的时候掉 volatile 怎么办?
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 的拷贝来确认。
关于c++ - 可以将 volatile const 的间接更改视为未定义行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31527499/