AutomaticReferenceCounting (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This code example indicates how the Automatic Reference Counting (ARC) mechanism manages objects' lifetimes. ARC is the default for the Delphi mobile 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

Personal tools
Assistance