Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2003-01

Dynamic Arrays (Pointers)

2 messages · 2 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

James Mills

Hi,

I'm using FPC 1.0.4

Would someone be so kind as to show me an example of using dynamic arrays of an object, creating new objects on the fly in code and disposing of them when they're no longer needed. Use of this would be in a irc services program I'm porting to linux from delphi (windows), ie: new nick joins server, create new object respresenting that nick...

Thank you
James

Unknown author
Show quoted text 5 lines
Would someone be so kind as to show me an example of using dynamic arrays of an object, creating new objects on the fly in code and disposing of them when they're no longer needed. Use of this would be in a irc services program I'm porting to linux from delphi (windows), ie: new nick joins server, create new object respresenting that nick...

To be honest, I would advise using a TList. This will do all the donley work for you, and even has a nice method 'pack' that will remove dead pointers for you. It doesn't sound like you need uber speed or anything, so even though the TList does add a slight performance hit over a dynamic array, the pro's outweigh the cons. All you would do is something like this, (TMYCLASSTYPE would be replaced with yout TObject descendent):

TWrapList = class
private
  FList: TList;
protected
  procedure SetListValue(Value: TMYCLASSTYPE); virtual;
  function  GetListValue(const Index: integer): TMYCLASSTYPE; virtual;
public
  property ListValues[index: integer]: TMYCLASSTYPE
           read GetListValue write SetListValue;
  constructor Create; virtual;
  destructor Destroy; override;
  function Count: integer;
  procedure Add(Item: TMYCLASSTYPE);
  procedure Delete(Index: Integer);
end;
constructor TWrapList.Create;
begin
  FList := TList.Create;
end;
destructor TWrapList.Destroy;
begin
  // NB: remember remove any items left in list....
  FList.free;
  inherited;
end;
procedure TWrapList.SetListValue(Value: TMYCLASSTYPE);
begin
  // NB. range checking will be usefull
  FList[index] := Value;
end;
function  TWrapList.GetListValue(const Index: integer): TMYCLASSTYPE;
begin
  Result := TMYCLASSTYPE( FList[index] );
end;
function TWrapList.Count: integer;
begin
  Result := FList.Count;
end;
procedure TWrapList.Add(Item: TMYCLASSTYPE);
begin
  FList.Add(Item); //if you make this a finction you can
                   //return the index here
end;
procedure TWrapList.Delete(Index: Integer);
begin
  FList.Delete(Index);
end;

This is a pattern I use all the time. It works well.

Matt

---------------------------------------------
This message was sent using Mistral WebMail.
http://www.mistral.co.uk/