[fpc-devel] ref count issue with out param

Florian Klämpfl florian at freepascal.org
Sat Jun 13 10:31:36 CEST 2015


Am 13.06.2015 um 09:56 schrieb Sven Barth:
> On 13.06.2015 06:04, Martin Frb wrote:
>> program Project1;
>>
>> procedure Foo1(a: AnsiString; out b: AnsiString);
>> begin
>>    WriteLn(length(a));  WriteLn(length(b));
>>    b := 'a';
>> end;
>>
>> procedure Foo2(out a: AnsiString; b: AnsiString);
>> begin
>>    WriteLn(length(a));  WriteLn(length(b));
>>    b := 'a';
>> end;
>>
>> const x: AnsiString = 'abcde';
>> var s1: AnsiString;
>> begin
>>    s1 := copy(x,2,3)+'x';
>>    Foo1(s1,s1);
>>
>>    s1 := copy(x,2,3)+'x';
>>    Foo2(s1,s1);
>>
>>    ReadLn;
>> end.
> 
> The answer is simple: Don't pass a variable you pass as an out-parameter also as a by-value or -
> even worse - const parameter. This is by design and an error in /your/ code.

It is similar to

type
  tarray = array [1..10] of longint;

procedure p(const a1 : tarray;var a2 : tarray);
  begin
    a2[1]:=4321;
    writeln(a1[1]);  // surprise
  end;

var
  arr : tarray;

begin
  arr[1]:=1234;
  p(arr,arr);
end.

The only way to prevent this (of course, such a simple case could be detected by the compiler but
one can always construct an example which works around this detection), is to turn off the const
optimization that const allows the compiler to pass only a reference, but I am pretty sure, people
will not be happy about this :)




More information about the fpc-devel mailing list