[fpc-devel] ref count issue with out param
Michael Van Canneyt
michael at freepascal.org
Sat Jun 13 16:12:52 CEST 2015
On Sat, 13 Jun 2015, Martin Frb wrote:
> "conts" param
> http://www.freepascal.org/docs-html/ref/refsu63.html#x166-17600014.4.4
> explicitly document that ref counting is not done. (But I have no const in my
> example)
>
> But "out" param have no such documentation. They also do *not* state in the
> doc that:
> 1) the ref count is decremented
> 2) May be decremented in a way that leaves other (ref counted) parameters in
> a zombie state (pointing to freed memory)
>
> In fact the doc states
>> The difference of out parameters and parameters by reference is very small:
>> the former gives the compiler more information about what happens to the
>> arguments when passed to the procedure: it knows that the variable does not
>> have to be initialized prior to the call. The following example illustrates
>> this:
> Yet "var" param also do not decrease the reference, so the statement is
> wrong/incomplete.
Well. First off, just so we can be clear. Things can be tested rather easily:
araminta: >cat trf.pp
{$mode objfpc}{$h+}
uses sysutils;
procedure DoByValue(S : String);
begin
Writeln('By value : ',StringRefCount(S));
end;
procedure DoConst(const S : String);
begin
Writeln('As Const : ',StringRefCount(S));
end;
procedure DoVar(var S : String);
begin
Writeln('By ref : ',StringRefCount(S));
end;
procedure DoOut(out S : String);
begin
Writeln('Out : ',StringRefCount(S));
end;
Var
S1,S2 : String;
begin
S1:=IntToStr(123)+'abc';
S2:=S1;
Writeln('Initial ref count : ',StringRefCount(S2));
DoByValue(S2);
DoConst(S2);
DoVar(S2);
DoOut(S2);
end.
araminta: >cat trf.pp
araminta: >./trf
Initial ref count : 2
By value : 3
As Const : 2
By ref : 2
Out : 0
Note the 0 !
Secondly, the section about 'out' parameters is very old; there were not nearly so much managed types at the time.
I will update it, I was just documenting the new string types anyway. The above will nicely illustrate the point.
Michael.
More information about the fpc-devel
mailing list