Starting with Delphi Berlin (10.1) the desktop compiler now also supports weak references.
You can read more about it here.
http://blog.marcocantu.com/blog/2016-ap ... ences.html.
Since we upgraded to Tokyo, I changed a few places where we were using Pointers to avoid circular references to use the new [weak] attribute instead.
However when I closed our app, madExcept reported memory leaks. According madExcept the leaks occur at the location where I changed the pointer to a weak reference.
So I started looking into it.
First I created a Unit Test. The test passes -> this means the [weak] attribute is working as expected.
If I comment out the [weak] attribute the test fails.
Code: Select all
procedure TTestWeakReferences.TestWeakReference;
var
Instance: ITestClass;
StrongReference: ITestClass;
[weak]
WeakReference: ITestClass;
begin
Instance := TTestClass.Create;
CheckRefCount(Instance, 1);
// strong reference -> RefCount must increase
StrongReference := Instance;
CheckRefCount(Instance, 2);
// weak reference -> RefCount must NOT change!
WeakReference := Instance;
CheckRefCount(Instance, 2);
// decrease RefCount by 1 -> WeakReference should still be valid
StrongReference := nil;
CheckNotNull(WeakReference);
// release all strong references -> object will be freed -> WeakReference should be set to nil
Instance := nil;
CheckNull(WeakReference);
end;
FParent is declared as:
[Weak] FParent: IJobComponent;
Exception does not fire. It does fire if I comment out the [weak] attribute.
So this is more proof, that the weak attribute is working as expected.
Code: Select all
procedure TJobComponent.SetParent(const Value: IJobComponent);
var
RefCount1: Integer;
RefCount2: Integer;
begin
if Assigned (Value) then
RefCount1 := (Value as TInterfacedObject).RefCount;
FParent := Value;
if Assigned (Value) then
begin
RefCount2 := (Value as TInterfacedObject).RefCount;
if RefCount1 <> RefCount2 then
raise Exception.Create(Format('Weak refrence failure for: [%s]. Before: %d. After: %d.', [(Value as TObject).ClassName, RefCount1, RefCount2]));
end;
end;
Thank you!