What's supposed to happen when using an object after FreeAndNil?

后端 未结 6 1839
轻奢々
轻奢々 2021-01-02 13:01

In my Delphi7 this code

var MStr: TMemoryStream;
...
FreeAndNil(MStr);
MStr.Size:=0; 

generates an AV: Access violation at address 0041D6D1

6条回答
  •  迷失自我
    2021-01-02 13:34

    Just to complicate the issue:

    If the method you call is a static (not virtual) method and it does not call any virtual methods itself nor does it access any fields of the object, you will not get an access violation even if the object reference has been set to NIL.

    The reason for this is that the access violation is caused by dereferencing the self pointer (in this case NIL), but that only happens when accessing a field or the object's VMT for calling a virtual method.

    This is just an exception to the rule that you cannot call methods of an NIL object reference that I'd like to mention here.

提交回复
热议问题