0

不使用 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.

在 main.m

    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 的摘录

当使用手动内存管理时,这种方法会出现问题。执行计算后,结果对象被分配并从方法返回。因为该方法必须返回那个对象,所以它不能释放它——这会导致它被立即销毁。解决此问题的最佳方法可能是自动释放对象,以便可以返回其值,并将其释放延迟到自动释放池耗尽为止。您可以利用 autorelease 方法返回其接收者并将其嵌入到如下表达式中这一事实:

Fraction *result = [[[Fraction alloc] init] autorelease]; 
//or like this: 
return [result autorelease];

注意:根据摘录似乎引用计数将是 2。如果是这样,请解释为什么?

4

1 回答 1

0

//THE ANSWER ASSUMES NO ARC AND AUTOMATIC GARBAGE COLLECTION

In add function : An instant of fraction class is created and the reference to it is stored in result. Since, alloc and init are used for creating that instant result becomes it's owner. And only an owner must release the object it owns when it's use is completed.But, the result doesn't release it (See add). Now add returns the reference to the object which was owned by result and it is stored in ans in main.m . Since, ans is not the owner of the object it has reference to and hasn't made any attempt to acquire, so the reference count of the object will be 1. Since, the the owner of this object can't be referenced any longer so, we can't release it. (Blah! a memory leak).
But what if we do [ans release]. Though it is bad practice. Can it save memory leak...
I think yes. Please comment if it won't

于 2013-09-23T10:23:48.280 回答