[fpc-pascal] How to work with reference-counted strings in dynamically created objects
Howard Page-Clark
hdpc at talktalk.net
Sat Mar 28 12:18:25 CET 2015
On 28/03/2015 08:31, Sven Barth wrote:
> Am 28.03.2015 06:51 schrieb "Howard Page-Clark" <hdpc at talktalk.net
> <mailto: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
>
Thank you
Howard
---
This email has been checked for viruses by Avast antivirus software.
http://www.avast.com
More information about the fpc-pascal
mailing list