Delphi dynamic array reference counter

Instead of using geneirc TList<integer> I decided to use

 TSolutions = array of integer; 

And then:

 function TEuclidMod.gcdExtended(p, q: integer): TSolutions; var tmpArr: TSolutions; begin SetLength(tmpArr, 3); if (q = 0) then begin tmpArr[0] := p; tmpArr[1] := 1; tmpArr[2] := 0; end else begin vals := gcdExtended(q, modulo(p,q)); tmpArr[0] := vals[0]; tmpArr[1] := vals[2]; tmpArr[2] := vals[1] - vals[2]*floor(p/q); end; Result := tmpArr; end; 

Variable vals: TSolutions; it is declared private in the class and inside the constructor I set its length.


I read in docwiki that dynamic arrays are counted, so I don't need to worry about their lives. To be sure that I wrote:

 constructor TEuclidMod.Create; begin SetLength(vals, 3); end; destructor TEuclidMod.Destroy; begin vals := nil; inherited; end; 

For now, this should be good; vals belongs to the class, and I free it from destroying the class. What about tmpArr ?

My function is working correctly. tmpArr is local, then I call SetLength, and I give it the length: this creates an array on the heap, if I'm not mistaken. But then when I return using Result := tmpArr , it is not deleted (tmpArr), since the function is out of scope? I don't want to return a dangling pointer or anything else! I must be sure that he is not released.

I think I'm safe because it is a function and it returns TSolution, so the reference count should always be at least. That's for sure? Basically: even if it is local, is it returning correctly?

But from what I found on SO, in this case

 procedure test; var a: TSolution; begin SetLength(a, 7); //do something end; 

a always freed when the procedure goes beyond!

+7
delphi
source share
1 answer

Dynamic arrays are counted by reference. Don't worry about memory management - just use them; what is the purpose of the reference counter. You do not need nil class fields in the destructor. The compiler will delete its reference counts when the object is destroyed.

But then, when I return with the result: = tmpArr, it is not deleted (tmpArr), since the function is out of scope?

Well, no, because you returned the array by assigning it to Result and, presumably, the caller also assigns the result of the new variable in turn. Naturally, the reference count will remain at least one if the caller does not assign the result of the function to a new variable.

+7
source share

All Articles