From 1ef78a214c26d3570783067f30cc00cb1a1eba36 Mon Sep 17 00:00:00 2001 From: Simon Byrne Date: Fri, 10 Feb 2023 11:17:29 -0800 Subject: [PATCH] Document WeakRef type (#48565) Fixes #26745. Based on suggestion by stevengj (https://github.com/JuliaLang/julia/issues/26745#issuecomment-379513967). --- base/gcutils.jl | 31 +++++++++++++++++++++++++++++++ base/weakkeydict.jl | 2 ++ doc/src/base/base.md | 1 + 3 files changed, 34 insertions(+) diff --git a/base/gcutils.jl b/base/gcutils.jl index 0e5d4c16e550a..a7cee0762bebe 100644 --- a/base/gcutils.jl +++ b/base/gcutils.jl @@ -1,5 +1,36 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license + +""" + WeakRef(x) + +`w = WeakRef(x)` constructs a [weak reference](https://en.wikipedia.org/wiki/Weak_reference) +to the Julia value `x`: although `w` contains a reference to `x`, it does not prevent `x` from being +garbage collected. `w.value` is either `x` (if `x` has not been garbage-collected yet) or `nothing` +(if `x` has been garbage-collected). + +```jldoctest +julia> x = "a string" +"a string" + +julia> w = WeakRef(x) +WeakRef("a string") + +julia> GC.gc() + +julia> w # a reference is maintained via `x` +WeakRef("a string") + +julia> x = nothing # clear reference + +julia> GC.gc() + +julia> w +WeakRef(nothing) +``` +""" +WeakRef + ==(w::WeakRef, v::WeakRef) = isequal(w.value, v.value) ==(w::WeakRef, v) = isequal(w.value, v) ==(w, v::WeakRef) = isequal(w, v.value) diff --git a/base/weakkeydict.jl b/base/weakkeydict.jl index 0a9987671ea9b..7cfc65ab0c66b 100644 --- a/base/weakkeydict.jl +++ b/base/weakkeydict.jl @@ -12,6 +12,8 @@ referenced in a hash table. See [`Dict`](@ref) for further help. Note, unlike [`Dict`](@ref), `WeakKeyDict` does not convert keys on insertion, as this would imply the key object was unreferenced anywhere before insertion. + +See also [`WeakRef`](@ref). """ mutable struct WeakKeyDict{K,V} <: AbstractDict{K,V} ht::Dict{WeakRef,V} diff --git a/doc/src/base/base.md b/doc/src/base/base.md index 7922dd7d67861..86218450bee4b 100644 --- a/doc/src/base/base.md +++ b/doc/src/base/base.md @@ -152,6 +152,7 @@ Base.promote Base.oftype Base.widen Base.identity +Base.WeakRef ``` ## Properties of Types