静态变量总是占用内存吗? [英] Will a static variable always use up memory?

查看:142
本文介绍了静态变量总是占用内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据讨论,我想知道函数作用域是否静态变量总是使用内存或者允许编译器优化。为了说明这个问题,假设一个类似这样的函数:

Based on this discussion, I was wondering if a function scope static variable always uses memory or if the compiler is allowed to optimize that away. To illustrate the question, assume a function like such:

void f() {
   static const int i = 3;
   int j = i + 1;
   printf("%d", j);
}

编译器很可能内联 i ,并且可能在编译时执行计算 3 + 1 。由于这是唯一使用 i 的值,因此不需要分配任何静态内存。因此,编译器允许优化静态变量,或者标准的任何静态变量都分配了内存。

The compiler will very likely inline the value of i and probably do the calculation 3 + 1 at compile time, too. Since this is the only place the value of i is used, there is no need for any static memory being allocated. So is the compiler allowed to optimize the static away, or does the standard mandate that any static variable has memory allocated?

推荐答案


因此,编译器允许优化static [...]。

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

根据标准:


国际标准定义一个
参数化非确定性抽象机。这个国际
标准没有要求符合
实现的结构。特别地,它们不需要复制或模拟抽象机的
结构。相反,符合实现
需要模拟(仅)抽象
机器的可观察行为,如下所述。5)

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)

...和脚注说:


5)这个规定有时被称为因为
实现可以不考虑这个
国际标准的任何要求,只要结果好像需要
已经被遵守,只要可以从可观察的$ b确定$ b程序的行为。例如,实际实现需要
不评估表达式的一部分,如果它可以推断其值是
未使用,并且没有影响程序的
的可观察行为的副作用产生。

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.

这意味着只要可观察的行为是相同的,编译器就可以做任何它想要的代码。因为你没有接受 static const 的地址,编译器可以将值优化为一个恒定积分表达式。​​

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.

这篇关于静态变量总是占用内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆