[fpc-devel] Managed types and reference counts revisited

Adriaan van Os fpc at microbizz.nl
Wed Aug 17 13:24:13 CEST 2016

Jonas Maebe wrote:
> Adriaan van Os wrote on Wed, 17 Aug 2016:
>> Either I am looking wrong (and missing the point) or the text at 
>> <http://www.freepascal.org/docs-html/ref/refse91.html> (a follow-up on 
>> <http://bugs.freepascal.org/view.php?id=26874>) is incorrect.
>> Doesn't the call to DoIt1(y,7) in procedure Test3 cause the reference 
>> count to be increased (from 0 to 1) and then decreased (from 1 to 0 
>> and thus disposed) ? And doesn't DoIt1 use value parameters ?
> Yes.
>> Therefore, doesn't the comment on  the const case (on the top of the 
>> page) belong to the value-parameter (aka "nothing") case ?
> It actually applies to both.
>> I would say, If const parameters, like var parameters, do nothing, 
>> there is no reference count decrease, therefore no dispose of classes 
>> (implementing an interface) even when the reference count is 0 ?
> It's about when you pass reference counted non-lvalues to parameters, 
> e.g. the result of a function or the expression "ClassInstance as 
> InterfaceType". In that case, the compiler will create a temp (on the 
> caller side) to store that function/expression result, which results the 
> reference count of the interface instance to be increased. After the 
> function call to which this interface instance has been passed as 
> parameter returns, the reference count will be decreased again because 
> the temp gets freed. If the reference count becomes 0 at that point, the 
> instance gets freed too. As a result, in this case even with a "const" 
> parameter you still have an interface instance that gets freed at some 
> point after the call (since otherwise there would be a memory/reference 
> count leak).
> Passing a class instance directly to a const interface parameter does 
> not result in the creation of a temp and hence does not result in 
> reference count increases/decreases. In case of a value parameter, there 
> is reference count on the callee side regardless of what you passed in.

Thanks for the clarification. I suggest the doc page 
<http://www.freepascal.org/docs-html/ref/refse91.html> to be changed accordingly.


Adriaan van Os

More information about the fpc-devel mailing list