gpt4 book ai didi

c++ - 标准在哪里定义 volatile 变量可以更改?

转载 作者:可可西里 更新时间:2023-11-01 16:37:58 25 4
gpt4 key购买 nike

标准在哪里定义volatile变量可以改变未被发现?

我找到了两个关于 volatile 的规范文本:

intro.execution/7 :

Reading an object designated by a volatile glvalue ([basic.lval]), modifying an object, calling a library I/O function, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression (or a subexpression) in general includes both value computations (including determining the identity of an object for glvalue evaluation and fetching a value previously assigned to an object for prvalue evaluation) and initiation of side effects. When a call to a library I/O function returns or an access through a volatile glvalue is evaluated the side effect is considered complete, even though some external actions implied by the call (such as the I/O itself) or by the volatile access may not have completed yet.

这一段是关于未检测到的变化吗? 副作用可能是这个意思吗?


或者有dcl.type.cv/5 :

The semantics of an access through a volatile glvalue are implementation-defined. If an attempt is made to access an object defined with a volatile-qualified type through the use of a non-volatile glvalue, the behavior is undefined.

这一段是关于我的问题的吗? “通过 volatile 泛左值进行访问的语义是实现定义的”到底是什么意思?您能举例说明不同的“访问语义”吗?


还有 dcl.type.cv/6 ,这是关于我的问题,但它只是一个注释:

[ Note: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. Furthermore, for some implementations, volatile might indicate that special hardware instructions are required to access the object. See [intro.execution] for detailed semantics. In general, the semantics of volatile are intended to be the same in C++ as they are in C. — end note ]

最佳答案

这里的关键是“执行环境状态的变化”。

执行环境是程序之外的环境。这可能包括操作系统、文件系统、屏幕等。这通常是不可预测的。您不能假设如果您将 0 写入文件,该文件将不会被另一个带有 1 的进程覆盖。

volatile 变量在逻辑上是该执行环境的一部分。就C++而言,环境可以枚举它们,读取它们,写入它们,就像文件一样。这可能会在您的程序不知情的情况下发生。

另一方面,您的实现实现了您的程序与其执行环境之间的链接,因此它确实对可能发生的事情有所了解。如果它有某种私有(private) RAM 磁盘实现,那么它可能知道某些文件名在操作系统文件系统中是不可见的。它可能知道 volatile int i 存在于 CPU 寄存器中,因此无法通过内存映射访问它。这都是 C++ 标准所允许的。只是笼统的讲了执行环境,执行起来一定要更精准。这就是“实现定义的语义”的意思。

关于c++ - 标准在哪里定义 volatile 变量可以更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51478636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com