問題描述
在 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.
這篇關于為什么全局變量和靜態變量被初始化為它們的默認值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!