在 Objective-C 中指望 int
s 总是被初始化为 0 是否安全?
更具体地说,当新实例化具有 int
ivars 的对象时,假设其 ivars 的值为 0 是否安全?
最佳答案
是的,类实例变量始终初始化为 0(或 nil
、NULL
或 false
,具体取决于确切的数据类型) .见 Objective-C 2.0 Programming Language :
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包含类似的引用:
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 类型也是如此:
// At global scope
int a_global_var; // guaranteed to be 0
NSString *a_global_string; // guaranteed to be nil
有一个异常(exception),对于局部变量,或者对于使用 malloc()
或 realloc()
分配的数据,它不为真; calloc()
也是如此,因为 calloc()
明确地将其分配的内存清零。
一个异常(exception)是,当启用自动引用计数 (ARC) 时,指向 Objective-C 对象的堆栈指针被隐式初始化为 nil
;但是,将它们显式初始化为 nil
仍然是一种好习惯。来自 Transitioning to to ARC Release Notes :
Stack Variables Are Initialized with
nil
Using ARC, strong, weak, and autoreleasing stack variables are now implicitly initialized with
nil
在 C++(以及 Objective-C++ 中使用的 C++ 对象)中,类实例变量也不零初始化。您必须在构造函数中显式初始化它们。
https://stackoverflow.com/questions/990817/