Explain circular references and how to break them

Also improves the documentation of `weakref`.
This commit is contained in:
Haoyu Qiu 2023-10-07 11:57:49 +08:00
parent e38686f85b
commit b2dcef4928
2 changed files with 2 additions and 1 deletions

View file

@ -1477,7 +1477,7 @@
<return type="Variant" />
<param index="0" name="obj" type="Variant" />
<description>
Returns a weak reference to an object, or [code]null[/code] if [param obj] is invalid.
Returns a [WeakRef] instance holding a weak reference to [param obj]. Returns an empty [WeakRef] instance if [param obj] is [code]null[/code]. Prints an error and returns [code]null[/code] if [param obj] is neither [Object]-derived nor [code]null[/code].
A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.
</description>
</method>

View file

@ -6,6 +6,7 @@
<description>
Base class for any object that keeps a reference count. [Resource] and many other helper objects inherit this class.
Unlike other [Object] types, [RefCounted]s keep an internal reference counter so that they are automatically released when no longer in use, and only then. [RefCounted]s therefore do not need to be freed manually with [method Object.free].
[RefCounted] instances caught in a cyclic reference will [b]not[/b] be freed automatically. For example, if a node holds a reference to instance [code]A[/code], which directly or indirectly holds a reference back to [code]A[/code], [code]A[/code]'s reference count will be 2. Destruction of the node will leave [code]A[/code] dangling with a reference count of 1, and there will be a memory leak. To prevent this, one of the references in the cycle can be made weak with [method @GlobalScope.weakref].
In the vast majority of use cases, instantiating and using [RefCounted]-derived types is all you need to do. The methods provided in this class are only for advanced users, and can cause issues if misused.
[b]Note:[/b] In C#, reference-counted objects will not be freed instantly after they are no longer in use. Instead, garbage collection will run periodically and will free reference-counted objects that are no longer in use. This means that unused ones will linger on for a while before being removed.
</description>