是否允许编译器删除无限循环像Intel C ++编译器-O2? [英] Are compilers allowed to remove infinite loops like Intel C++ Compiler with -O2 does?
问题描述
以下测试代码在VS中正确地使用调试或发布以及GCC。它对于具有调试的ICC也是正确的,但是在启用优化( -O2
)时不会正确。
The following testing code does correctly in VS either with debug or release, and also in GCC. It also does correctly for ICC with debug, but not when optimization enabled (-O2
).
#include <cstdio>
class tClassA{
public:
int m_first, m_last;
tClassA() : m_first(0), m_last(0) {}
~tClassA() {}
bool isEmpty() const {return (m_first == m_last);}
void updateFirst() {m_first = m_first + 1;}
void updateLast() {m_last = m_last + 1;}
void doSomething() {printf("should not reach here\r\n");}
};
int main() {
tClassA q;
while(true) {
while(q.isEmpty()) ;
q.doSomething();
}
return 1;
}
isEmpty())。然而,当在ICC(发布)下启用 -O2
时,它会无限地开始doSomething。
It is supposed to stop at while(q.isEmpty())
. When -O2
enabled under ICC (release), however, it starts to "doSomething" infinitely.
是单线程程序, isEmpty()
应该被计算为 true
发现没有理由ICC应该这样行事?因为 while(q.isEmpty()); $ ...(q.isEmpty()),因此我会错过任何东西吗?
Since this is single-threaded program and isEmpty()
should be evaluated as true
, I can find no reason the ICC should behave in this way? Do I miss anything?
推荐答案
c $ c> loop不包含可能导致外部可见的副作用的语句,整个循环被优化为不存在。原因也一样:
Because the while (q.isEmpty()) ;
loop contains no statements that can ever cause an externally-visible side-effect, the entire loop is being optimised out of existence. It's the same reason that:
for (int i = 0; i < 10; i++)
;
可以优化出来,只要 i
不是 volatile
(存储到 volatile
对象是程序的外部可见效果的一部分) 。
could be optimised out of existence, as long as i
was not volatile
(stores to volatile
objects are part of the "externally visible" effects of a program).
在C语言中,它实际上是一个突出的骨头,关于是否允许以这种方式优化无限循环(我不知道什么情况是用C ++)。据我所知,在这个问题上从未达成共识 - 聪明和知识渊博的人已经采取了双方。
In the C language, it is actually an outstanding bone of contention as to whether an infinite loop is allowed to be optimised away in this manner (I do not know what the situation is with C++). As far as I know, a consensus has never been reached on this issue - smart and knowledgeable people have taken both sides.
这篇关于是否允许编译器删除无限循环像Intel C ++编译器-O2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!