Should I put a try-finally block after every Object.Create?

后端 未结 8 1370
青春惊慌失措
青春惊慌失措 2021-02-04 17:11

I have a general question about best practice in OO Delphi. Currently, I put try-finally blocks anywhere I create an object to free that object after usage (to avoid memory leak

8条回答
  •  一整个雨季
    2021-02-04 17:56

    Yes it is always a good idea (essential) if the code that creates the object is responsible for free'ing it. If not, then try/finally isn't appropriate but then again neither is .Free in any case!

    However, it can be cumbersome to have this boilerplate code peppering your "business logic", and you might want to consider an approach which has the same guarantee of freeing your objects but which is much cleaner (and has other benefits), such as my own AutoFree() implementation.

    With AutoFree() your code could then be written:

    aObject := TObject.Create;
    AutoFree(@aObject);
    
    aObject.AProcedure();
    

    or alternatively, since the implementation uses a reference to a reference (to enable auto-NIL'ing as well as Free'ing), you can even pre-register your references that you wish to be AutoFree'd to keep such housekeeping declarations away from your business logic and keep the real "meat" of your code as clean as possible (this is especially beneficial when potentially multiple objects need to be Free'd):

    AutoFree(@aObject1);
    AutoFree(@aObject2);
    
    aObject1 := TObject.Create;
    aObject1.AProcedure();
    
    // Later on aObject2 is (or may be) also created
     :
    

    Not shown in my original posting is a later addition to the mechanism to support registering multiple references in a single AutoFree() call, but I'm sure you can figure out the changes needed to support this on your own, if you wish to be able to do this:

    AutoFree([@aObject1, @aObject2]);
    
    aObject1 := TObject.Create;
    aObject1.AProcedure();
    
    // Later on aObject2 is (or may be) also created
     :
    

提交回复
热议问题