Raffaele Rossi
Raffaele Rossi

Reputation: 3137

Delphi collection of objects

I have created an easy class called TIstruzione; I need to create 4 objects at runtime and store them in an array so that I can access them when I want.

FList: TObjectList<TIstruzione>;

I have created this in the public section of TForm1 because I have seen in Delphi's documentation that this is an apposite generic container for classes. Then I am going to manage his lifetime in this way:

procedure TForm1.FormCreate(Sender: TObject);
begin
 FList.Create;
 FList.OwnsObjects := true;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
 FList.Destroy;
end;

The OwnsObject ensures that the objects are owned by the list and when I free the list, the objects inside are freed as well. Am I correct?

If you look at the code here, I am trying to populate the list:

procedure TForm1.Button1Click(Sender: TObject);
var a: TIstruzione;
begin

 a := TIstruzione.Create;
 try
  a.tipo := Add;
  a.rdest := 2;
  a.dato1 := 7;
  a.dato2 := 5;
  FList.Add(a);
 finally
  a.Free;
 end;

  a := TIstruzione.Create;
 try
  a.tipo := Load;
  a.rdest := 1;
  a.dato1 := 2;
  a.dato2 := -1;
  FList.Add(a);
 finally
  a.Free;
 end;

end;

I have an error when the program starts. It is an access violation; any idea? Just to be complete, the class is simply this:

type

 TTipo = (RISC_Add, RISC_AddI, RISC_Sub, RISC_SubI, RISC_Load, RISC_Store);
 TPip = (MIPS_pipeline, PPC_pipeline);

type
 TIstruzione = class
  public
   tipo: TTipo;
   rdest: integer;
   dato1: integer;
   dato2: integer;
 end;

Upvotes: 0

Views: 4522

Answers (1)

Rudy Velthuis
Rudy Velthuis

Reputation: 28826

Make that:

FList := TObjectList<TIstruzione>.Create;

You should never call Create on a variable, always use the proper constructor syntax, like above.

Also, don't Free the item you just added to the list:

procedure TForm1.Button1Click(Sender: TObject);
var 
  a: TIstruzione;
begin
  a := TIstruzione.Create;
  a.tipo := Add;
  a.rdest := 2;
  a.dato1 := 7;
  a.dato2 := 5;
  FList.Add(a);

  a := TIstruzione.Create;
  a.tipo := Load;
  a.rdest := 1;
  a.dato1 := 2;
  a.dato2 := -1;
  FList.Add(a);
end;

The TObjectList is now the owner, so the objects will be freed by the TObjectList, and should not be freed not by you anymore. That is what OwnsObjects := True; means.

Upvotes: 5

Related Questions