问题描述
在 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吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!