Ugochukwu Mmaduekwe 42 Posted February 12, 2020 Hi all, is it possible to have an array of weak references in Delphi, or a container that does not affect the reference count of the object been added to it? Share this post Link to post
Fr0sT.Brutal 900 Posted February 12, 2020 Sure, just cast them to Pointer Share this post Link to post
Stefan Glienke 2014 Posted February 12, 2020 (edited) 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 February 12, 2020 by Stefan Glienke 3 1 Share this post Link to post
Ugochukwu Mmaduekwe 42 Posted February 12, 2020 @Fr0sT.Brutal, @Stefan Glienke, Thanks a lot for your answers. will give it a try. Thanks once again. Share this post Link to post
Fr0sT.Brutal 900 Posted February 13, 2020 @Stefan Glienke thanks, I thought a general term was meant not the language construction. Haven't looked at these new features yet Share this post Link to post