Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely Create and Free multiple objects in Delphi

Tags:

delphi

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?

like image 341
Eric G Avatar asked Oct 04 '11 05:10

Eric G


1 Answers

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.

like image 156
chuckj Avatar answered Sep 19 '22 16:09

chuckj