Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

testing object variable 1

Status
Not open for further replies.

rbow

Programmer
Aug 23, 2002
4
HU
Hi,

I have two object variables (a1, a2: TObject)
referencing to the same object instance.
There is a chance in the program flow
(depends on a condition)
when the object instance has to destroyed (FreeAndNil(a1)).
Later how can I test the a2 variable,
whether it references a valid object instance or does not.
I have tried the 'is' operator (if a2 is TObject then...),
but the result was True in case of a destroyed
object as well.

Thanks,
rbow
 
Hi,

that would be if Assigned(a2) then ....
make sure that you destroy objects this way :

FreeAndNil(a1);

or

a1.Free;
a1:=nil; (this code does the same as FreeandNil)

greetings,


 
Hi,

Thanks for the answer!
I've tried your suggestion, but it didn't work.

Here is my code:

var
a1 , a2: TObject;
begin
a1 := TObject.Create;
a2 := a1;
FreeAndNil(a1);
if Assigned(a2) then
ShowMessage('Error!')
else
ShowMessage('OK');
end;

I gave the 'Error!' message...
What's wrong?

rbow
 
a2 := a1 is assigning to a2 the content of a1. After freeing a1 it become nil, but a2 continue holding the old adress a1 was holding.

So Assigned(a2) will be true and it is correct: a2 is NOT nil.

Say:
a1 := TObject.Create; //a1 <- $xxxx (object address)
a2 := a1; // a2 <- $xxxx
FreeAndNil(a1); // a1 <- NIL but a2 still $xxxx.

If you have a pointer to an object, check the original object to see if it is freed, not the pointer to it.

Note: your test code rely upon the &quot;Optimization&quot; directive... it will show you some thing when optimized and another thing when not optimized. In any case it will work the same, but trying to peek into the vars will show different things. To see what is really going on turn off the optimization.

HTH.
buho (A).
 
Thanks the answers!
I workaround the problem with reorganizing
the code.

rbow
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top