[fpc-pascal] Freeing memory with exceptions

Michael Van Canneyt michael at freepascal.org
Wed May 24 15:46:11 CEST 2023

On Wed, 24 May 2023, Hairy Pixels via fpc-pascal wrote:

>> 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.

I see no problem, I am used to this.

This is Pascal, you need to manage your memory and hence your references, 
this is true even in the absence of exceptions: In your example you would
also need to remember to remove your instance from the list after you free
it, even if there are no exceptions.

That is why I usually use TComponent as a base class. It has an owner-owned
concept and when you free the toplevel component, all children are also
freed. It also has a "free notification" mechanism: when a referenced object 
is freed, you can get notified and can take appropriate action.

If you use that correctly, there is very little to worry about.


More information about the fpc-pascal mailing list