c++ - 可以将 volatile const 的间接更改视为未定义行为吗?

标签 c++ c volatile undefined-behavior

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?

Compilable code

最佳答案

当您尝试修改“初始”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/

相关文章:

c++ - 析构函数调用 "Stopped working"错误

c++ - 为什么需要第二个 cin.ignore() ?

c - 数组到函数 C

c# - 如果我调用 Thread.Join() 是否需要 volatile?

c++ - 如何获取12 :00PM of the day的SYSTEM时间

c - 如何将迭代函数转换为递归函数?

c - 为什么 clang 和 gcc 会产生次优输出(复制结构)以将指针传递给按值结构 arg?

c - C 中 *((volatile UINT32*)(a)) 的含义

java - jmx 是否为每次调用创建一个新线程?

c++ - 在返回对象引用的 Python 中调用 C++ DLL