[fpc-pascal] Freeing memory with exceptions
    Hairy Pixels 
    genericptr at gmail.com
       
    Wed May 24 15:34:12 CEST 2023
    
    
  
> On May 21, 2023, at 11:03 PM, Michael Van Canneyt via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
> 
> They're used all over the place in the RTL and FCL, so you better take them
> into account.
> 
> The compiler will do this wrapping anyway if you use ansistrings, so the
> approach with e.g. a generic record will not cause a lot of overhead in most
> cases.
I wanted to add to my example. What about this? The exception now provides a challenge to clean up without ARC in all places. Very risky right? My sense is that exceptions are only safe for fully ARC languages or garbage collected.
var
  obj: TObject;
begin
  try
    obj := TObject.Create;
    // This object list will free the items in another part of the program
    if CheckSomething(...) then
      begin
        list.Add(obj);
       addedToList := true;
    end;
   // maybe we passed it to another class also...
    // Raises an exception in another unit, caller doesn't know!
    DoThis;
  finally
    // we need to remember to remove the item from the list now and
    // what happens if we passed the reference to another class?
    // we need to check if this actually happened also so declare a local var to check
    if addedToList then
      list.Delete(..);
    if passedToOtherClass then
      otherClass.obj := nil;
    obj.Free;
  end;
end.
Regards,
Ryan Joseph
    
    
More information about the fpc-pascal
mailing list