I have never used FreeAndNil but have always thought that it checks the
pointer before calling free.
IT DOES NOT - I looked at the code! (at least in D7).
Where ever
Object.Free;
Object := nil;
would cause an exception, so would
FreeAndNil(Object);
And it is not "Object Oriented" (not an issue for me - the issue for me
is why remember FreeAndNil when O. Free; O := nil; is the same).
Doug
Rob Kennedy wrote:
> (Top-posting fixed.)
> Doug Hale wrote:
>
>> Rob Kennedy wrote:
>>
>>> David Smith wrote:
>>>
>>>> I usually follow what every example in Delphi manual does. There are
>>>> certain cases where freeAndNil can cause an access violation:
>>>>
>>>> Object.Free;
>>>> Object := nil;
>>>>
>>> In what way do those two lines make FreeAndNil cause an access violation?
>>>
>> If Object does not actually point to a valid object instance,
>> Object.Free will cause an access violation.
>>
>> For example:
>> Object.Free;
>> Object.Free;
>> The second Free will fault.
>>
>
> Of course.
>
> Am I to understand that you're really not making any statement at all
> about FreeAndNil? You haven't shown any examples of calling FreeAndNil,
> and you haven't shown anything that would cause exceptions in FreeAndNil
> that wouldn't also occur without FreeAndNil.
>
> Your original statement made it sound like there are ways to cause
> access violations in FreeAndNil that wouldn't occur in ordinary code,
> and the colon at the end of your statement introduced those two lines as
> an example of such code.
>
> There _are_ ways to cause FreeAndNil to fail that wouldn't fail
> otherwise, but none of the code you've shown demonstrates that.
>
>