[fpc-devel] Defer keyword

Ryan Joseph genericptr at gmail.com
Thu May 6 17:38:59 CEST 2021


Something which annoys me about Pascal is cleanup in which a function exits in multiple places but there is no formal way to free memory which may be used in the current scope. I say ultimately Pascal needs some opt-in automatic reference counting for TObject but the "defer" keyword would be helpful alternative to what we have now, which is nothing.

The concept is very easy to understand and should be easy to implement by simply making a "defer" statement node which is added to a list and then called during function finalization like the other ref counted objects (dynamic array, interfaces etc....).

I've seen it appear in multiple languages already and it's a sound idea in my opinion. Is this something worth perusing for Pascal?

https://www.hackingwithswift.com/example-code/language/how-to-delay-execution-of-code-using-the-defer-keyword
https://www.geeksforgeeks.org/defer-keyword-in-golang/

procedure DoStuff;
begin
  obj := TObject.Create;
  defer objects.Free;

  while true do
    begin
      // don't worry, obj will be freed safely
      if not obj.TrySomething then
        exit;
    end;
end;

Regards,
	Ryan Joseph



More information about the fpc-devel mailing list