Results 1 to 3 of 3

Thread: TLists, destroying classes and sleep() problems?

  1. #1

    TLists, destroying classes and sleep() problems?

    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.

    Code:
    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.

    Code:
    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?
    - In a world without the wall and fences, who will need the Gates and Windows.

  2. #2

    TLists, destroying classes and sleep() problems?

    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:

    [pascal]
    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;
    [/pascal]
    Feel the power of Open Source.
    <br />Feel the power of Free Pascal.

  3. #3

    TLists, destroying classes and sleep() problems?

    Quote Originally Posted by Almindor
    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:

    [pascal]
    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;
    [/pascal]
    This code will fail if the list only contains one element.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •