<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Sat, Sep 27, 2014 at 4:36 PM, Sven Barth <span dir="ltr"><<a href="mailto:pascaldragon@googlemail.com" target="_blank">pascaldragon@googlemail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">
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).</blockquote></div><br><div class="gmail_default" style="font-family:trebuchet ms,sans-serif">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.<br><br></div><div class="gmail_default" style="font-family:trebuchet ms,sans-serif">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.<br><br></div><div class="gmail_default" style="font-family:trebuchet ms,sans-serif">--Constantine<br></div></div></div>