Best practice to do nested TRY / FINALLY statement

前端 未结 6 996
逝去的感伤
逝去的感伤 2020-12-04 16:07

Hi What is the best way to do nested try & finally statements in delphi?

var cds1  : TClientDataSet;
    cds2  : TClientDataSet;
    cds3  : TClientDataS         


        
6条回答
  •  一整个雨季
    2020-12-04 16:26

    @mghie: Delphi has got stack allocated objects:

    type
      TMyObject = object
      private
        FSomeField: PInteger;
      public
        constructor Init;
        destructor Done; override;
      end;
    
    constructor TMyObject.Init;
    begin
      inherited Init;
      New(FSomeField);
    end;
    
    destructor TMyObject.Done;
    begin
      Dispose(FSomeField);
      inherited Done;
    end;
    
    var
      MyObject: TMyObject;
    
    begin
      MyObject.Init;
      /// ...
    end;
    

    Unfortunately, as the above example shows: Stack allocated objects do not prevent memory leaks.

    So this would still require a call to the destructor like this:

    var
      MyObject: TMyObject;
    
    begin
      MyObject.Init;
      try
        /// ...
      finally
        MyObject.Done;
      end;
    end;
    

    OK, I admit it, this is very nearly off topic, but I thought it might be interesting in this context since stack allocated objects were mentioned as a solution (which they are not if there is no automatic destructor call).

提交回复
热议问题