Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>Free</code> has some special logic: it checks to see whether <code>Self</code> is <code>nil</code>, and if so, it returns without doing anything -- so you can safely call <code>X.Free</code> even if <code>X</code> is <code>nil</code>. This is important when you're writing destructors -- David has more details in <a href="https://stackoverflow.com/a/8550628/87399">his answer</a>.</p> <p>You can look at the source code for <code>Free</code> to see how it works. I don't have the Delphi source handy, but it's something like this:</p> <pre><code>procedure TObject.Free; begin if Self &lt;&gt; nil then Destroy; end; </code></pre> <p>Or, if you prefer, you could think of it as the equivalent code using <a href="http://docwiki.embarcadero.com/VCL/en/System.Assigned" rel="nofollow noreferrer"><code>Assigned</code></a>:</p> <pre><code>procedure TObject.Free; begin if Assigned(Self) then Destroy; end; </code></pre> <p>You can write your own methods that check for <code>if Self &lt;&gt; nil</code>, as long as they're <a href="http://docwiki.embarcadero.com/RADStudio/en/Methods#Static_Methods" rel="nofollow noreferrer">static (i.e., not <code>virtual</code> or <code>dynamic</code>) instance methods</a> (thanks to David Heffernan for the documentation link). But in the Delphi library, <code>Free</code> is the only method I know of that uses this trick.</p> <p>So you don't need to check to see if the variable is <code>Assigned</code> before you call <code>Free</code>; it already does that for you. That's actually why the recommendation is to call <code>Free</code> rather than calling <code>Destroy</code> directly: if you called Destroy on a <code>nil</code> reference, you would get an access violation.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload