[fpc-pascal] How to work with reference-counted strings in dynamically created objects

Sven Barth pascaldragon at googlemail.com
Sat Mar 28 09:31:12 CET 2015


Am 28.03.2015 06:51 schrieb "Howard Page-Clark" <hdpc at talktalk.net>:
>
> The following program, compiles and runs as expected using a shortstring
declaration in the TExample record.
> Could someone explain how to adapt it to cope with a TExample record
containing ansistrings?

[snip]
> procedure TExampleList.Initialize(aCount: integer);
> var
>   i: integer;
>   pex: PExample;
> begin
>   for i:=1 to aCount do begin
>     GetMem(pex, SizeOf(TExample));
// use New(pex) instead of GetMem(...)
>     pex^.Init(Format('Example#%d, Value=%d',[i, Random(100)]));
>     FList.Add(pex);
>   end;
> end;
>
[snip]

>
> destructor TExampleList.Destroy;
> var
>   i: integer;
> begin
>   for i:=0 to FList.Count-1 do
>     Freemem(FList[i], SizeOf(TExample));
// Use Dispose(PExample(FList[i])) instead of FreeMem(...)
>   FList.Free;
>   inherited Destroy;
> end;
>

It's best to always use New/Dispose if you work with records. Use
GetMem/FreeMem only if you work with unstructured memory areas or where you
don't really know the real size beforehand.

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20150328/827490d4/attachment.html>


More information about the fpc-pascal mailing list