为什么全局变量和静态变量被初始化为它们的默认值?
在 C/C++ 中,为什么将全局变量和静态变量初始化为默认值?
In C/C++, why are globals and static variables initialized to default values?
为什么不只留下垃圾值呢?有什么特别的吗这是什么原因?
Why not leave it with just garbage values? Are there any special reasons for this?
推荐答案
安全:单独保留内存会泄漏其他进程或内核的信息.
Security: leaving memory alone would leak information from other processes or the kernel.
效率:这些值在初始化为某些东西之前是无用的,并且在具有展开循环的块中将它们归零更有效.操作系统甚至可以在系统空闲时将空闲列表页面归零,而不是在某些客户端或用户等待程序启动时.
Efficiency: the values are useless until initialized to something, and it's more efficient to zero them in a block with unrolled loops. The OS can even zero freelist pages when the system is otherwise idle, rather than when some client or user is waiting for the program to start.
可再现性:不考虑这些值会使程序行为不可重复,从而导致很难发现错误.
Reproducibility: leaving the values alone would make program behavior non-repeatable, making bugs really hard to find.
优雅:如果程序可以从 0 开始,而不必使用默认初始化程序使代码混乱,那就更干净了.
Elegance: it's cleaner if programs can start from 0 without having to clutter the code with default initializers.
然后人们可能想知道为什么 auto
存储类 确实 开始时是垃圾.答案有两个:
One might then wonder why the auto
storage class does start as garbage. The answer is two-fold:
它没有,在某种意义上.每个级别的第一个堆栈帧页面(即添加到堆栈的每个新页面)确实收到零值.同一堆栈级别的后续函数实例看到的垃圾"或未初始化"值实际上是您自己的程序及其库的其他方法实例留下的先前值.
It doesn't, in a sense. The very first stack frame page at each level (i.e., every new page added to the stack) does receive zero values. The "garbage", or "uninitialized" values that subsequent function instances at the same stack level see are really the previous values left by other method instances of your own program and its library.
可能会有二次(或其他)运行时性能损失与将 auto
(函数局部变量)初始化为任何内容相关联.一个函数可能不会使用任何或所有大数组,比如说,在任何给定的调用中,它可能被调用数千或数百万次.静态和全局的初始化,OTOH,只需要发生一次.
There might be a quadratic (or whatever) runtime performance penalty associated with initializing auto
(function locals) to anything. A function might not use any or all of a large array, say, on any given call, and it could be invoked thousands or millions of times. The initialization of statics and globals, OTOH, only needs to happen once.
相关文章