请关于这段代码: type TClient = class(TObject) public Host: String; Queue: TIdThreadSafeStringList; end;var Clients: TThreadList;procedure TMain.FormCreate(Sender: TObject);const Hosts: Array[0..4] of String = ( 'HOST1', 'HOST2', 'H
type TClient = class(TObject) public Host: String; Queue: TIdThreadSafeStringList; end; var Clients: TThreadList; procedure TMain.FormCreate(Sender: TObject); const Hosts: Array[0..4] of String = ( 'HOST1', 'HOST2', 'HOST3', 'HOST4, 'HOST5' ); var I: Integer; List: TList; Client: TClient; begin Clients := TThreadList.Create; Clients.Duplicates := dupAccept; for I := Low(Hosts) to High(Hosts) do begin Client := TClient.Create; Client.Host := Hosts[I]; Client.Queue := TIdThreadSafeStringList.Create; Clients.Add(Client); Client := nil; end; end;
我想知道释放内存的正确方法是:
procedure TMain.FormDestroy(Sender: TObject); var I: Integer; List: TList; begin List := Clients.LockList; try for I := 0 to List.Count - 1 do TClient(List[I]).Free; finally Clients.UnlockList; Clients.Free; end; end;
或者像这样:
procedure TMain.FormDestroy(Sender: TObject); var I: Integer; List: TList; begin List := Clients.LockList; try for I := 0 to List.Count - 1 do begin TClient(List[I]).Queue.Free; TClient(List[I]).Free; end; finally Clients.UnlockList; Clients.Free; end; end;
换句话说,我想知道当我释放一个对象(TClient)时,是自动释放所有元素(队列),还是必须手动执行.
谢谢!
客户端对象被销毁时,需要销毁队列对象.但是,正确的方法是让客户端类负责其成员.type TClient = class private FHost: String; FQueue: TIdThreadSafeStringList; public constructor Create(const Host: string); destructor Destroy; override; end; .... constructor TClient.Create(const Host: string); begin inherited Create; FQueue := TIdThreadSafeStringList.Create; FHost := Host; end; destructor TClient.Destroy; begin FQueue.Free; inherited; end;
如果你这样做,那么就不可能实例化类并且无法实例化其成员.按照自己的方式执行,每次需要实例化类时,都必须重复代码来实例化成员.通过这种方式犯错很容易.更重要的是它使代码更难以阅读和维护.