[fpc-devel] Suggestion: reference counted objects

Constantine Yannakopoulos alfasud.ti at gmail.com
Sat Sep 27 17:00:47 CEST 2014


On Sat, Sep 27, 2014 at 4:36 PM, Sven Barth <pascaldragon at googlemail.com>
wrote:

> There are however some nasty problems inside constructors and destructors,
> because "Self" is reference counted as well (and should be after all as we
> don't want the instance to be destroyed behind our backs suddenly).


The parenthesis can happen in Delphi interfaced objects as well. It is
perfectly possible to lose the object from under your feet if the code of
one of its methods ‚Äčleads to references reaching zero (e.g. removal from a
strong-ref'd list). If such a possibility exists the developer needs to
manually _AddRef/_Release (e.g. store Self in a local interface variable)
if they need to access Self after that point, and that is perfectly OK. The
only way to avoid that would be to emit code at a compiler-generated
implicit try-finally block to _AddRef/_Release, which is a bad idea IMHO as
it adds overhead when it won't be required for 99.99% of cases.

As for destructors, the way refcounting is implemented in Delphi it
prohibits performing _Addref/_Release (e.g. pass an interface variable of
Self to an external method) in them because this will cause infinite
recursion. This problem has an easy solution: Override BeforeDestruction
and set RefCount to a positive value, 1 or MaxInt div 2 (not -1, consider
the sequence _AddRef[0], _AddRef[1], _Release[0-bang], _Release[AV]) after
calling inherited (which checks for 0). Since the object destruction
process has already started due to RefCount reaching zero, refcounting is
useless at this point and can be safely disabled. You could consider doing
this in your implementation.

--Constantine
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20140927/f89ee951/attachment.html>


More information about the fpc-devel mailing list