[fpc-devel] ref count issue with out param

Martin Frb lazarus at mfriebe.de
Sat Jun 13 15:09:47 CEST 2015

On 13/06/2015 09:31, Florian Klämpfl wrote:
> 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 :)

Out of curiosity, how would you disguise it from the compiler?
Actually, how would you do that in the example I posted. In your example 
it is not that hard to discuise (but then in your example there is 
nothing unexpected)

But in my example it is about refcounting (and pointing to unallocated mem)

   //procedure Foo2(out a: AnsiString; b: AnsiString);

Foo2 is called with
1) the same string for both param
2) That string has a ref count of 1 before the call

How to you disguise it, without incrementing the ref count)
If the refcount goes up, then all is ok, both arguments will be valid 
(that is either nil, or some string in allocated memory).

Also the behaviour is not documented. 

"conts" param 
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 

More information about the fpc-devel mailing list