PDA

View Full Version : TLists, destroying classes and sleep() problems?



FusionWolf
08-02-2005, 01:30 AM
Hello fellow coders,

I have stored couple instances of class to the Tlist. Now I want to free the first instance of class and delete it from TList and then execute some method from second instance of class. So the code looks something like this.



procedure SomeProcedure;
begin
TMyClass(List.Items[0]).Free;
List.Delete(0);
TMyClass(List.Items[0]).SomeMethod;
end;


Now when SomeProcedure() is executed all goes well, but the SomeMethod() which is executed there is the method of the instance of class which I just freed and deleted there?!?

BUT, if I put sleep() call before SomeMethod() call then the executed method is correct from correct instance. Like This.



procedure SomeProcedure;
begin
TMyClass(List.Items[0]).Free;
List.Delete(0);
Sleep(500);
TMyClass(List.Items[0]).SomeMethod;
end;


So it seems that, it takes some time for Tlist to delete TMyClass instance from the list (execute its destructor). So how I know when the list is ready to call SomeMethod()? I think that declaring sleep() is not good because the time may vary from computer to another. And because we're talking about game here, so it should be as quick as possible. Any suggessions?

Almindor
17-02-2005, 08:55 PM
Remember that TList has pointers in it, not object, and it doesn't free them by itels.

However it seems to me like a bug to me(are you using Delphi or FPC?)
In any case there's a better solution:


procedure SomeProcedure;
begin
List:=TObjectList.Create; // note: DON'T use TObjectList.Create(false);
... // Add things to list
List[0].Delete;
TMyClass(List[0]).DoSomething;
List.Free;
end;

marcov
21-02-2005, 07:49 AM
Remember that TList has pointers in it, not object, and it doesn't free them by itels.

However it seems to me like a bug to me(are you using Delphi or FPC?)
In any case there's a better solution:


procedure SomeProcedure;
begin
List:=TObjectList.Create; // note: DON'T use TObjectList.Create(false);
... // Add things to list
List[0].Delete;
TMyClass(List[0]).DoSomething;
List.Free;
end;


This code will fail if the list only contains one element.