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!