整体是否始终初始化为0? [英] Are ints always initialized to 0?
问题描述
是否可以安全地依靠 int
在Objective-C中始终被初始化为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-all,即除了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
Apple似乎已删除上述文件(现已关联)到Wayback机器)。 (当前)有效文档使用Objective-Programming编程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.
但是,对于类的实例变量,这只是 true;对于在全局范围内声明的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 $ c $隐式初始化强,弱和自动释放堆栈变量c>
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!