Objective c 目标C中关于引用计数的内存管理
不使用ARC或自动垃圾收集Objective c 目标C中关于引用计数的内存管理,objective-c,memory-management,Objective C,Memory Management,不使用ARC或自动垃圾收集 -(Fraction*) add: (Fraction*) f { Fraction *result = [[Fraction alloc] init]; //To do return result; } //after the function returns. What will the reference count of object
-(Fraction*) add: (Fraction*) f
{
Fraction *result = [[Fraction alloc] init];
//To do
return result;
}
//after the function returns. What will the reference count
of object that result was pointing to. See main.m below.
大体上
int main(int argc, char* argv[])
{
//To do
Fraction *ans = [[Fraction alloc] init];
ans = [f1 add: f2];
//I guess that the refrence count of the object that ans will be pointing
after this statement will be 1 or 2.
//...
}
//stephen kochan objective-c中关于这一点的摘录
使用手动内存管理时,此方法会出现问题。执行计算后,将分配result对象并从方法返回。因为该方法必须返回该对象,所以不能释放该对象,否则会导致该对象当场被销毁。解决此问题的最佳方法可能是自动释放对象,以便返回其值,并将其释放延迟到自动释放池耗尽为止。您可以利用autorelease方法返回其接收器并将其嵌入如下表达式中的事实:
Fraction *result = [[[Fraction alloc] init] autorelease];
//or like this:
return [result autorelease];
注:根据摘录,参考计数似乎为2。如果是这样,请解释原因?//答案假设没有ARC和自动垃圾收集
-(Fraction*) add: (Fraction*) f
{
Fraction *result = [[Fraction alloc] init];
//To do
return result;
}
//after the function returns. What will the reference count
of object that result was pointing to. See main.m below.
在添加功能中:
创建一个瞬间分数类,对它的引用存储在result
中。因为,alloc和init
用于创建即时result
成为其所有者。并且只有所有者必须在其使用完成时释放其拥有的对象。但是,结果
不会释放它(请参见添加)
。现在add返回对result
所拥有的对象的引用,它存储在ans
的main.m
中。由于ans不是它引用的对象的所有者,并且没有尝试获取该对象,因此该对象的引用计数将为1。由于无法再引用此对象的所有者,因此我们无法释放它。(废话!内存泄漏)。
但是如果我们这样做呢。虽然这是一个坏习惯。它可以节省内存泄漏
我想是的。如果不会的话,请发表评论在目标C中有很多关于内存管理的类似问题。请看一个例子。@Carlvaezey我希望得到这样的答案。如果我错了,请纠正我。