How should you safely create and free multiple objects?
Basically, this sort of thing:
newOrderSource := TWebNewOrderSource.Create();
twData := TTWData.Create();
webData := TWebData.Create();
try
//do stuff
finally
newOrderSource.Free();
twData.Free();
webData.Free();
end;
In this case, the second and third create commands aren't safe, as they work with a database. Should I just put all the Creates in the try block and check if they are assigned before I call free on them?
You can do this with one try block if you assign nil to the variables first like,
newOrderSource := nil;
twData := nil;
webData := nil;
try
newOrderSource := TWebNewOrderSource.Create();
twData := TTWData.Create();
webData := TWebData.Create();
//do stuff
finally
webData.Free();
twData.Free();
newOrderSource.Free();
end;
This works because Free()
checks Self
for nil
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With