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.

IN 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];

注 : 抽出によると、refrence カウントは 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 に答える