gpt4 book ai didi

c++ - 关于循环变量优化的标准合规行为是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:24:54 24 4
gpt4 key购买 nike

在下面的循环中

int i = 0;
// pass address of i to some other part of the program
// Do some work
for (; i < 10;)
{
// Do some more work

function_that_increments_i();
}

如果出于某些(奇怪的,理论上的)原因,编译器优化了 i 的内存读取在i < 10并且总是读取第一个加载的值,这种行为是否符合标准?我想知道 C++ 语言的哪一部分描述了这种情况下的行为。

编辑:在与@Rakete1111 讨论后,我希望专家对以下语言及其含义进行解释:

The least requirements on a conforming implementation are:

(7.1) — Accesses through volatile glvalues are evaluated strictly according to the rules of the abstract machine.

(7.2) — At program termination, all data written into files shall be identical to one of the possible results that execution of the program according to the abstract semantics would have produced.

(7.3) — The input and output dynamics of interactive devices shall take place in such a fashion that prompting output is actually delivered before a program waits for input. What constitutes an interactive device is implementation-defined.

These collectively are referred to as the observable behavior of the program. [ Note: More stringent correspondences between abstract and actual semantics may be defined by each implementation. —end note ]

按照我的解释,这允许读取 i待优化。我在这里缺少什么?

最佳答案

C++ 标准描述了一个抽象的虚拟机,如果源代码根据其规则有效,它就会按照其描述的方式运行程序。实际的 C++ 编译器是实现与标准中描述的虚拟机尽可能接近的环境的代码。虽然该标准很少提及特定的优化,但它确实需要编译器实现:

4.6 第 5 段:

A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input. However, if any such execution contains an undefined operation, this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation).

在您的情况下,如果编译器无法查看 function_that_increments_i() 定义,那么它无法证明不会修改 i,并且必须悲观地/防御性地假设它确实如此,并且不应用具有此先决条件的修改。

但是,如果 function_that_increments_i() 的定义是可见的,可以内联,并且它不会将对 i 的引用传递给它无法跟踪的其他函数,那么它仍然可以应用一系列内联/减少优化.一旦删除了对 function_that_increments_i() 的调用,就有可能消除(或更改 i 的表示形式)。

重要的是它必须保持相同的行为。

关于c++ - 关于循环变量优化的标准合规行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48598240/

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