Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to free an object which is in a record?
    text
    copied!<p>Here I have a tricky situation, I guess. I need to be able to free an object which is a field of a record. I would normally write the cleanup code in the destructor, if it was a class. But since record types can't introduce a "destructor", how would it be possible to call <strong>TObject(Field).Free;</strong> ?</p> <p>There'll be two types of usage I predict:</p> <ol> <li><p>Replacing the record with a new one.</p> <p>I think this usage would be easy to implement. Since records are value types and so they are copied on assignment, I can overload the assigning operator and free the objects owned by old record.</p> <p>( <strong>Edit:</strong> Assignment overloading wasn't able. That's a new info to me.. )</p></li> <li><p>Exiting the scope where record variable defined.</p> <p>I can think of a private method that frees the objects and this method could be called on scope excitation manually. BUT, here is the same question: How to make it more <strong>recordly</strong>? This behaviour kind of feels like a class...</p></li> </ol> <p>Here is a sample (and obviously <strong>not the intended usage</strong>):</p> <pre><code>TProperties = record ... some other spesific typed fields: Integers, pointers etc.. FBaseData: Pointer; FAdditionalData: TList&lt;Pointer&gt;; //FAdditionalData: array of Pointer; this was the first intended definition end; </code></pre> <p>Assume,</p> <pre><code>FAdditionalData:=TList&lt;Pointer&gt;.Crete; </code></pre> <p>called in record constructor or manually in record variable scope by accessing the field publicly like</p> <pre><code>procedure TFormX.ButtonXClick(Sender: TObject); var rec: TProperties; begin //rec:=TProperties.Create(with some parameters); rec.FAdditionalData:=TList&lt;Pointer&gt;.Create; //do some work with rec end; </code></pre> <p>After exiting the ButtonClick scope the <strong>rec</strong> is no more but a <strong>TList</strong> still keeps its existance which causes to memory leaks...</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