Objects in R are considered reachable if they can be accessed by following
a chain of references, starting from a root node; root nodes are
specially-designated R objects, and include the global environment and base
environment. As long as the key is reachable, the value will not be garbage
collected. This is true even if the weak reference object becomes
unreachable. The key effectively prevents the weak reference and its value
from being collected, according to the following chain of ownership:
weakref <- key -> value.
When the key becomes unreachable, the key and value in the weak reference
object are replaced by
NULL, and the finalizer is scheduled to execute.
new_weakref(key, value = NULL, finalizer = NULL, on_quit = FALSE)
The key for the weak reference. Must be a reference object -- that is, an environment or external pointer.
The value for the weak reference. This can be
A function that is run after the key becomes unreachable.
Should the finalizer be run when R exits?
e <- env() # Create a weak reference to e w <- new_weakref(e, finalizer = function(e) message("finalized")) # Get the key object from the weak reference identical(wref_key(w), e)#>  TRUE# When the regular reference (the `e` binding) is removed and a GC occurs, # the weak reference will not keep the object alive. rm(e) gc()#> used (Mb) gc trigger (Mb) limit (Mb) max used (Mb) #> Ncells 834754 44.6 1496242 80 NA 1496242 80 #> Vcells 1590894 12.2 8388608 64 16384 3657397 28identical(wref_key(w), NULL)#>  TRUE# A weak reference with a key and value. The value contains data about the # key. k <- env() v <- list(1, 2, 3) w <- new_weakref(k, v) identical(wref_key(w), k)#>  TRUEidentical(wref_value(w), v)#>  TRUE#> used (Mb) gc trigger (Mb) limit (Mb) max used (Mb) #> Ncells 834825 44.6 1496242 80 NA 1496242 80 #> Vcells 1590559 12.2 8388608 64 16384 3657397 28#>  TRUE#> used (Mb) gc trigger (Mb) limit (Mb) max used (Mb) #> Ncells 834842 44.6 1496242 80 NA 1496242 80 #> Vcells 1590581 12.2 8388608 64 16384 3657397 28identical(wref_key(w), NULL)#>  TRUEidentical(wref_value(w), NULL)#>  TRUE