Multiobject try..finally

Just a simple Delphi pattern. We all have encountered nested try..finally blocks like this:

CChar := TTextTableCursor.Create(TChar);
try
 CCharProp := TTextTableCursor.Create(TCharProp);
 try
   Builder := TCharPropBuilder.Create(Result);
   try
     //Do some work with all three objects
     //Since all three are needed, we can't destroy any before this point
   finally
     FreeAndNil(Builder);
   end;
 finally
   FreeAndNil(CCharProp);
 end;

finally

 FreeAndNil(CChar);

end;But there's a nicer way of doing the same while still being exception safe (and avoiding the overhead of three try..finally exception frames):

CChar := nil;
CCharProp := nil;
Builder := nil;
try
 CChar := TTextTableCursor.Create(TChar);
 CCharProp := TTextTableCursor.Create(TCharProp);
 Builder := TCharPropBuilder.Create(Result);
//Do some work with all three objects

finally

 FreeAndNil(Builder);
 FreeAndNil(CCharProp);
 FreeAndNil(CChar);

end;

Напишите комментарий:

Если хотите, можно залогиниться.

*