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

Howard Page-Clark hdpc at talktalk.net
Sat Mar 28 06:50:58 CET 2015


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?

Howard

== code ==

program Project1;

{$mode objfpc}{$H+}
{$ModeSwitch advancedrecords}

uses classes, sysutils;

type

   { TExample }

   TExample = record
     text: string; // program performs flawlessly with shortstring;
     procedure Init(const aText: string);
   end;
   PExample = ^TExample;

   { TExampleList }

   TExampleList = class(TObject)
   private
     FList: TFPList;
     procedure Initialize(aCount: integer);
   public
     constructor Create;
     destructor Destroy; override;
     procedure ListItems;
   end;

{ TExampleList }

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

constructor TExampleList.Create;
begin
   FList:=TFPList.Create;
   Randomize;
   Initialize(4);
end;

destructor TExampleList.Destroy;
var
   i: integer;
begin
   for i:=0 to FList.Count-1 do
     Freemem(FList[i], SizeOf(TExample));
   FList.Free;
   inherited Destroy;
end;

procedure TExampleList.ListItems;
var
   i: integer;
begin
   for i:=0 to FList.Count-1 do
     WriteLn(PExample(FList[i])^.text);
   ReadLn;
end;

{ TExample }

procedure TExample.Init(const aText: string);
begin
   text:=aText;
end;


var
   exampleList: TExampleList;

begin
   exampleList:=TExampleList.Create;
   exampleList.ListItems;
   exampleList.Free;
end.




---
This email has been checked for viruses by Avast antivirus software.
http://www.avast.com




More information about the fpc-pascal mailing list