Raffaele Rossi
Raffaele Rossi

Reputation: 3127

Delphi dynamic array of classes

I am doing a program that solves a system of Congruences (Algebra) and I have created a class called TCongruence with constructor, functions, class functions and so on. I have declared a private variable:

private
 x: array of TCongruence;

When I try to fill this array I am writing this code:

counter := counter + 1;
SetLength(x, counter);
x[counter-1] := TCongruence.Create(...);

I have understood that this code works after some time I have spent on these 3 lines because my original code was something like this:

counter := counter + 1;
SetLength(x, counter);
tmp := TCongruence.Create(...);
x[counter-1] := tmp;

Of course I have tmp: TCongruence. Why is the second block of code wrong? Class are references so I thought that I could do something like that given the fact that I am not calling Free on tmp.


Wrong = at compile time it's good but at runtime when I access the array I have weird values.

Upvotes: 3

Views: 4876

Answers (2)

EugeneK
EugeneK

Reputation: 2224

You can just write x := x + [TCongruence.Create(..)], it is more readable.

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 612914

There is no practical difference between the two variants. It seems a little wasteful to assign to a intermediate local variable, but it won't change the behaviour of your program.

If there is a difference in behaviour, then that will be due to other factors, in the rest of your program that we cannot see.

Finally, growing arrays one element at a time is a little clunky, potentially slow, and can result in fragmented memory. It would make more sense, typically, to use a class like TList<TCongruence> or TObjectList<TCongruence>. Then you could write:

List.Add(TCongruence.Create(...))

Upvotes: 4

Related Questions