Will a static variable always use up memory?

夙愿已清 提交于 2019-12-05 22:43:58

So is the compiler allowed to optimize the static away[...] ?

Yes. According to the Standard:

1.9 Program Execution

The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.5)

...and the footnote says:

5) This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program. For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.

What this all means is that the compiler can do anything it wants to your code so long as the observable behavior is the same. Since you haven't take the address of the static const, the compiler can optimize the value away to a Constant Integral Expression.

According to section 1.8 The C++ object model n3242

An object has a type and a storage duration (optionally a name).
It does not require a memory location unless its address is taken.

No, it will not always use memory. My GCC version 4.5.2 produces code with real global variable on -O0, but uses directly inline constant 4 when compiled with `-O3'

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!