http://docwiki.embarcadero.com/RADStudio/Seattle/en/Automatic_Reference_Counting_in_Delphi_Mobile_Compilers#Weak_References

Weak References

Another important concept for ARC is the role of weak references, which you can create by tagging them with [weak] attribute. Suppose that two objects refer to each other using a field, and an external variable refers to the first. The reference count of the first object will be 2 (the external variable, and the second object), while the reference count of the second object is 1. Now, as the external variable goes out of scope, the two objects' reference count remains 1, and they remain in memory indefinitely.

To solve this type of situation, and many similar scenarios, is to use a weak reference to break the circular references when the last external reference goes out of scope.

A weak reference is a reference to an object that does not increase its reference count. To declare a weak reference, use the [weak] attribute, supported by the Delphi mobile compilers.

Given the previous scenario, if the reference from the second object back to the first one is weak, as the external variable goes out of scope, both objects are destroyed. Here is an example of this situation:

type
TMyComplexClass = class;
 
TMySimpleClass = class
private
[Weak] FOwnedBy: TMyComplexClass;
public
constructor Create();
destructor Destroy (); override;
procedure DoSomething(bRaise: Boolean = False);
end;
 
TMyComplexClass = class
private
fSimple: TMySimpleClass;
public
constructor Create();
destructor Destroy (); override;
class procedure CreateOnly;
end;

In the following code snippet, the constructor of the complex class creates an object of the other class:

constructor TMyComplexClass.Create;
begin
inherited Create;
FSimple := TMySimpleClass.Create;
FSimple.FOwnedBy := self;
end;

Remember that the FOwnedBy field is a weak reference, so it does not increase the reference count of the object it refers to, in this case the current object (self).

Given this class structure, we can write:

class procedure TMyComplexClass.CreateOnly;
var
MyComplex: TMyComplexClass;
begin
MyComplex := TMyComplexClass.Create;
MyComplex.fSimple.DoSomething;
end;

This causes no memory leak, given that the weak reference is properly used.

As a further example of the use of weak references, note this code snippet in the Delphi RTL, part of the TComponent class declaration:

type
TComponent = class(TPersistent, IInterface,
IInterfaceComponentReference)
private
[Weak] FOwner: TComponent;

If you use the weak attribute in code compiled by one of the desktop Delphi compilers, the attribute is ignored. Using DCC32, you have to make sure that you add the proper code in the destructor of an "owner" object to also free the "owned" object. Calling Free is allowed, although the effect is different in the Delphi mobile compilers. The behavior is correct in both in most circumstances.

Note: When an instance has its memory released, all active [weak] references are set to nil. Just as a strong (normal) reference, a [weak] variable can only be nil or reference a valid instance. This is the main reason why a weak reference should be assigned to a strong reference before being tested for nil and dereferenced. Assigning to a strong reference does not allow the instance to be released prematurely.

var
O: TComponent;// a strong reference
begin
O := FOwner; // assigning a weak reference to a strong reference
if O <> nil then
O.<method>;// safe to dereference
end;

Note: You can only pass a [Weak] variable to a var or out parameter that is also marked as [Weak]. You cannot pass a regular strong reference to a [Weak] var or out parameter.

Weak References的更多相关文章

  1. [翻译]Understanding Weak References(理解弱引用)

    原文 Understanding Weak References Posted by enicholas on May 4, 2006 at 5:06 PM PDT 译文 我面试的这几个人怎么这么渣啊 ...

  2. 【翻译】C# Tips & Tricks: Weak References - When and How to Use Them

    原文:C# Tips & Tricks: Weak References - When and How to Use Them Sometimes you have an object whi ...

  3. Understanding Weak References

    Understanding Weak References Posted by enicholas on May 4, 2006 at 5:06 PM PDT Some time ago I was ...

  4. [转]Understanding Weak References

    原文地址:https://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html 推荐另一篇文章:http://www ...

  5. lua weak table 概念解析

    lua weak table 经常看到lua表中有 weak table的用法, 例如: weak_table = setmetatable({}, {__mode="v"}) 官 ...

  6. strong & weak

    Here is a quick summary: A strong reference will keep the object it points to from being deallocated ...

  7. Lua中的weak表——weak table

    弱表(weak table)是一个很有意思的东西,像C++/Java等语言是没有的.弱表的定义是:A weak table is a table whose elements are weak ref ...

  8. Lua中的weak表——weak table(转)

    弱表(weak table)是一个很有意思的东西,像C++/Java等语言是没有的.弱表的定义是:A weak table is a table whose elements are weak ref ...

  9. OC对象之旅 weak弱引用实现分析

    Runtime学习 -- weak应用源码学习   Runtime源码分析,带你了解OC实现过程.其中参考了大量的大神的代码以及文献,里面也有个人的见解,欢迎拍砖,欢迎交流. 两种常见使用场景 /// ...

随机推荐

  1. GCD基础

    一.GCD介绍 1.what is GCD? Grand Central Dispatch 中枢调度器.用很简单的方式实现了极为复杂繁琐的多线程编程.异步执行任务的技术之一.   2.GCD存在于li ...

  2. C++中atof函数的实现和atoi的实现

    在C++中有两个系统函数可以实现字符串转浮点型和字符串转整形,下面实现一下这两个函数. #include <iostream> #include <string> using ...

  3. Failed to read schema document

    转自:http://eric-yan.iteye.com/blog/1908470 问题描述: web项目web.xml编译错误: schema_reference.4: Failed to read ...

  4. jquery 给新增的addClass 使用css样式

    假如有一个情况,当导航url找不到相同的地址,就会出现找不到地址,高亮当前导航不出现 解决 办法 记得使用文档载入完成后执行的函数. 因为 .current 是 addClass 新增的class $ ...

  5. Django的url别名功能的使用

    - URL: from django.urls import reverse url(r'^all/(?<article_type_id>\d+).html$', home.index, ...

  6. python pandas 对各种文件的读写 IO tools

    The pandas I/O API is a set of top level reader functions accessed like pd.read_csv() that generally ...

  7. bzoj1087互不侵犯King(状压)

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1087 简单的状压dp.但是wa了好几发.注意long long. 注意0和0的连边.而且不能 ...

  8. zk中文乱码问题

    之前讲了怎么把数据导入到zookeeper(见zookeeper事件监听的importData方法),虽然本机win10的zookeeper展示没问题,但到了linux上就出现乱码了: << ...

  9. NoClassDefFoundError: org/apache/juli/logging/LogFactory

    将 apache-tomcat-7.0.8\lib 下的 tomcat-util.jar添加到 注:不是 直接在 configure build path 中添加 jar

  10. 最近遇到的几个纯C编程的陷阱

    首先是一个不容易看出来的语法上的陷阱 经过调试得出的错误是对非socket的socket操作出错,sockfd在调试过程中发现是0,不是一个合理的文件描述符. 仔细一看原来是括号忘记加了,该运算是先用 ...