Delphi Berlin 10.1 compiler introduces weak references...

The Delphi compiler in Berlin 10.1 introduces the concept of weak references.

With reference to the code below, without the [weak] attribute, when one and two is nil'd, the destructor is not called. With the [weak] attribute, the destructor is called. So, the weak references in the Delphi wiki now extends to Win32/Win64 (possibly iOS/OSX too?)

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  IMyInterface = interface
    procedure AddObjectRef(AMyInterface: IMyInterface);
  end;

  TObjectOne = class (TInterfacedObject, IMyInterface)
  private
    FName: string;
    [weak]anotherObj: IMyInterface;
  public
    procedure AddObjectRef(AMyInterface: IMyInterface);
    constructor Create(const AName: string);
    destructor Destroy; override;
  end;

procedure main;
var
  one, two: IMyInterface;
begin
  one := TObjectOne.Create('one');
  two := TObjectOne.Create('two');
  one.AddObjectRef (two);
  two.AddObjectRef (one);
  two := nil;
  one := nil;
end;

{ TObjectOne }

procedure TObjectOne.AddObjectRef(AMyInterface: IMyInterface);
begin
  anotherObj := AMyInterface;
end;

constructor TObjectOne.Create(const AName: string);
begin
  inherited Create;
  FName := AName;
end;

destructor TObjectOne.Destroy;
begin
  WriteLn(FName, ' is being destroyed');
  inherited;
end;

begin
  main;
end.
Published Sun, 16 Oct 2016 @ 1:39 PM by chuacw
Related articles:

Leave a Comment

(required) 
(required) 
(optional)
(required) 
Enter the following code to ensure that your comment reaches the intended party:
Enter the numbers you see in the image: