Jump to content

Recommended Posts

1 hour ago, Fr0sT.Brutal said:

Sure, just cast them to Pointer

Nope, that would be an array of unsafe references - an important characteristic of a weak reference is that it will be cleared when the referenced instance gets destroyed.

 

Since you cannot declare TArray<[weak]IInterface> or something like that you need to make a record type with a weak reference field.

 

Since Object ARC will be history with 10.4 I don't care - but weak reference for interfaces will still be a thing:

 

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

type
  weakref = record
    [weak]
    ref: IInterface;
    class operator Implicit(const value: IInterface): weakref; inline;
    class operator Implicit(const value: weakref): IInterface; 
  end;

class operator weakref.Implicit(const value: IInterface): weakref;
begin
  Result.ref := value;
end;

class operator weakref.Implicit(const value: weakref): IInterface;
begin
  Result := value.ref;
end;

procedure Test;
var
  refs: TArray<IInterface>;
  weaks: Tarray<weakref>;
  intf: IInterface;
begin
  SetLength(refs, 3);
  refs[0] := TInterfacedObject.Create;
  refs[1] := TInterfacedObject.Create;
  refs[2] := TInterfacedObject.Create;

  SetLength(weaks, 3);
  weaks[0] := refs[0];
  weaks[1] := refs[1];
  weaks[2] := refs[2];

  refs := nil;
  Writeln(Assigned(IInterface(weaks[0])));
  Writeln(Assigned(IInterface(weaks[1])));
  Writeln(Assigned(IInterface(weaks[2])));
end;

begin
  Test;
end.

FWIW Spring4D has Weak<T> that works for interfaces and objects and has the added feature that when used for objects on non ARC platform it also clears then and thus protects against dangling references.

Edited by Stefan Glienke
  • Like 3
  • Thanks 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×