問題描述
在 Objective-C 中指望 int
s 總是被初始化為 0 是否安全?
Is it safe to count on int
s always being initialized to 0 in Objective-C?
更具體地說,當新實例化具有 int
ivars 的對象時,假設其 ivars 的值為 0 是否安全?
More specifically, when an object with int
ivars has been newly instantiated, is it safe to assume that its ivars have value 0?
推薦答案
是的,類實例變量總是初始化為0(或nil
、NULL
或false
,具體取決于確切的數據類型).請參閱 Objective-C 2.0 編程語言:
Yes, class instance variables are always initialized to 0 (or nil
, NULL
, or false
, depending on the exact data type). See the Objective-C 2.0 Programming Language:
alloc
方法為新對象的實例變量動態分配內存,并將它們全部初始化為 0 — 全部,即除了連接新實例的 isa
變量到它的類.
The
alloc
method dynamically allocates memory for the new object’s instance variables and initializes them all to 0—all, that is, except theisa
variable that connects the new instance to its class.
<小時>
編輯 2013-05-08
蘋果似乎已經刪除了上述文件(現在鏈接到 The Wayback Machine).(當前)活動文檔 Programming With Objective-C 包含類似的引用:
alloc
方法還有另一項重要任務,即通過將對象屬性設置為零來清除分配給對象屬性的內存.這避免了內存包含以前存儲的垃圾的常見問題,但不足以完全初始化對象.
The
alloc
method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero. This avoids the usual problem of memory containing garbage from whatever was stored before, but is not enough to initialize an object completely.
<小時>
但是,這僅對于類的實例變量是正確的;對于在全局范圍內聲明的 POD 類型也是如此:
However, this is only true for instance variables of a class; it is also true for POD types declared at global scope:
// At global scope
int a_global_var; // guaranteed to be 0
NSString *a_global_string; // guaranteed to be nil
有一個例外,對于局部變量,或者對于使用 malloc()
或 realloc()
分配的數據,它不為真;calloc()
也是如此,因為 calloc()
明確地將其分配的內存清零.
With one exception, it is not true for local variables, or for data allocated with malloc()
or realloc()
; it is true for calloc()
, since calloc()
explicitly zeros out the memory it allocates.
一個例外是,當啟用自動引用計數 (ARC) 時,指向 Objective-C 對象的堆棧指針被隱式初始化為 nil
;但是,將它們顯式初始化為 nil
仍然是一種好習慣.來自 過渡到 ARC 發行說明:
The one exception is that when Automatic Reference Counting (ARC) is enabled, stack pointers to Objective-C objects are implicitly initialized to nil
; however, it's still good practice to explicitly initialize them to nil
. From the Transitioning to to ARC Release Notes:
堆棧變量用 nil
使用 ARC,強、弱和自動釋放堆棧變量現在使用 nil
Using ARC, strong, weak, and autoreleasing stack variables are now implicitly initialized with nil
在 C++(以及 Objective-C++ 中使用的 C++ 對象)中,類實例變量也不零初始化.您必須在構造函數中顯式初始化它們.
In C++ (and C++ objects being used in Objective-C++), class instance variables are also not zero-initialized. You must explicitly initialize them in your constructor(s).
這篇關于整數總是初始化為0嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!