[fpc-pascal] Arrays of objects
Joao Morais
post at joaomorais.com.br
Wed Oct 31 12:48:45 CET 2007
Adrian Maier wrote:
> On 10/31/07, Joao Morais <post at joaomorais.com.br> wrote:
>> Adrian Maier wrote:
>>> On 10/31/07, Matt Emson <memsom at interalpha.co.uk> wrote:
>>>> Adrian Maier wrote:
>>>>> Hello,
>>>>>
>>>>> I'm seeking for advice about which is the best way to hold an array of
>>>>> class instances
>>>>> I need to access the elements using its position (like a regular
>>>>> array) , and also i'd like
>>>>> the structure to grow when I add more elements
>>>> TObjectList
>>> I am aware that TObjectList is one of the possible ways.
>>> But I was hoping to get a better understanding about the purpose of these
>>> various classes or types of array , and more importantly what are the
>>> drawbacks .
>>>
>>> Is there really no wiki page , tutorial, anything that provides an overview of
>>> the collections and types of arrays that FPC has ?
>> You can use dynamic arrays, they work like an ansi string:
>>
>> var
>> VArray: array of TSomeClass;
>> begin
>> SetLength(VArray, 10);
>> // now you have VArray[0] .. VArray[9];
>> SetLength(VArray, 20);
>> // now you have [0] .. [19];
>> // Length(VArray) = 20
>> // for I := 0 to Pred(Length(VArray)) is a valid statement
>>
>> They are reference counted, just like ansi strings, ie don't worry about
>> memory leakages.
>
> The detail that is not crystal clear to me is : after the first SetLength
> and i set the first 3 elements, is it *guaranteed* that the
> second SetLength leaves those first 3 elements untouched?
I don't use dyn array realocation by myself, but seeing this piece of
code I'd assume yes:
procedure TFPList.SetCapacity(NewCapacity: Integer);
begin
If (NewCapacity < FCount) or (NewCapacity > MaxListSize) then
Error (SListCapacityError, NewCapacity);
if NewCapacity = FCapacity then
exit;
ReallocMem(FList, SizeOf(Pointer)*NewCapacity);
FCapacity := NewCapacity;
end;
--
Joao Morais
More information about the fpc-pascal
mailing list