AutomaticReferenceCounting (Delphi)

From RAD Studio Code Examples

Description

This code example indicates how the Automatic Reference Counting (ARC) mechanism manages objects' lifetimes.

Note: ARC is the default memory management model of the previous Delphi mobile compilers (RAD Studio versions XE4 through 10.3). In current releases, the Delphi mobile compilers use the same manual memory management as the desktop compilers.

Code

uses
  System.SysUtils;

type
  TMySimpleClass = class
  private
    //
    stringMember: String;
    constructor Create(Text: String);
  end;

constructor TMySimpleClass.Create(Text: String);
begin
  stringMember := Text;
end;

procedure SampleARC(ref: TMySimpleClass);
var
  localObj1, localObj2: TMySimpleClass;
begin
  // After the following assignments, the reference count should be 4.
  // Two references coming from localObj1 and localObj2, and one from passing the object to the procedure.
  localObj1 := ref;
  localObj2 := localObj1;
  // By the moment the end statement has been passed in this procedure,
  // the Automatic Reference Counting mechanism will manage the memory automatically.
end;

var
  myObject: TMySimpleClass;

begin
  // The reference count for the newly created object is 1.
  myObject := TMySimpleClass.Create
    ('This is a code example for Automatic Reference Counting');
  SampleARC(myObject);

  // The reference count is still 1.
end.
// Ending the program will release the object from the memory.

Uses

See Also