Hi davelane,
Maybe it is useful to think of pointers instead of:
var
myClass: TMyClass; // Pointer to TMyClass, 4 Byte
myClass := TMyClass.Create; // Get new TMyClass obeject, like new in C++
myClass.Destroy; // Free memory
myClass := Nil; // Set pointer to Nil
myClass_2 := myClass; // Copy pointers
If you Nil every instance after destroying it this should work:
myClass.Destroy;
myClass := Nil; // = FreeAndNil
...
if Assigned(myClass) then myClass.DoIt;
But this should not:
procedure foo(aClass: TMyClass);
begin
aClass.Destroy;
aClass := Nil;
end;
...
foo(myClass);
In foo you destroy the object aClass points to but you set aClass (a local pointer on the stack) to Nil. myClass is still <> Nil!
Hope this helps,
Alex
Main Topics
Browse All Topics





by: andrewjbPosted on 2003-01-22 at 06:01:50ID: 7780496
Nope - no way at all. It's up to you to make sure you don't retain dangling pointers when you've freed the object. Setting the appropriate reference variable to nil immediately after the free helps for the immediate pointer, but not others.
var a : tSomeObject;
b : tSomeObject;
a := tSomeObject.Create;
b := a;
a.Free;
a := nil;
// Easy to spot
but b still points to the old position.
Actually, you might manage to have some sort of class function that can tell you. e.g. have a master list of all created objects of a class (so the constructor adds itself to the list; the destructor removes itself) then a class function can check if 'self' is in the list.... it'd sort of work.