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

后端 未结 8 1368
青春惊慌失措
青春惊慌失措 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 18:06

    If you're creating the object in a class's constructor and the object will be owned by the enclosing class, you'll want to free it in the owning class's destructor.

    I tend to use FreeAndNil() instead of calling Free.

    EDIT: But as others have said, you definitely always want to free what you create.

    0 讨论(0)
  • 2021-02-04 18:07

    To answer part two of your question:
    try finally hardly has any overhead.

    In fact there are plenty of methods having an implicit try...finally block. For instance just having a function using a local var of any Interface type and assigning that a value has.

    --jeroen

    0 讨论(0)
提交回复
热议问题