How to safely Create and Free multiple objects in Delphi

前端 未结 2 1507
灰色年华
灰色年华 2021-01-11 13:41

How should you safely create and free multiple objects?

Basically, this sort of thing:

  newOrderSource := TWebNewOrderSource.Create();
  twData := T         


        
2条回答
  •  失恋的感觉
    2021-01-11 13:54

    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.

提交回复
热议问题