[fpc-devel] Suggestion: reference counted objects

Hans-Peter Diettrich DrDiettrich1 at aol.com
Sat Sep 27 21:22:12 CEST 2014


Marco van de Voort schrieb:
> In our previous episode, Sven Barth said:
>>> It looks to me like inside methods Self doesn't deserve refcounting,
>>> because a method can be invoked only with an existing instance, which
>>> will stay alive at least until the call returns.
>> That's the thing I'm not yet entirely sure about. Though disabling it 
>> for Self would definitely simplyfy things. I'll simply give it a try and 
>> then my constructor problems should hopefully be solved as well...
> 
> Methods might return SELF as function result?

Yes, and this might be a problem during and immediately following 
construction. When the constructor passes Self to another procedure, 
that procedure must not do anything that increases and later decreases 
the refcount. Increasing the refcount during construction might help, 
but then the refcount cannot be decremented at the end of the 
constructor. And what should happen to the result of Create?
   MyObj := TMyObj.Create;
is fine when the refcount is increased to 1 when the instance is 
assigned to MyObj. In contrast
   TMyObj.Create;
looks somewhat useless, and how to destroy this zombie later, without 
refcounting? This construct might be legal with TThread.Create? Can 
somebody test what Delphi does in this case?

Suggestion:
The constructor inits the refcount to 1, and decrements it on exit - 
*not* using _Release! This will prevent destruction by refcounting 
during construction.
The compiler uses (always, or only with latter syntax?) a hidden local 
variable, where a new reference is stored and refcounted. This will 
destroy an zombie on exit from the subroutine (maybe unit initialization!).


Another one - weak references:
When the compiler only handles immediate assignments to weak references, 
such a variable cannot be passed as VAR, because the called code cannot 
know about that special handling.

DoDi




More information about the fpc-devel mailing list