Finalization of Objects

Share:

Description

Registers an R function to be called upon garbage collection of object or (optionally) at the end of an R session.

Usage

1
  reg.finalizer(e, f, onexit = FALSE)

Arguments

e

Object to finalize. Must be an environment or an external pointer.

f

Function to call on finalization. Must accept a single argument, which will be the object to finalize.

onexit

logical: should the finalizer be run if the object is still uncollected at the end of the R session?

Details

The main purpose of this function is to allow objects that refer to external items (a temporary file, say) to perform cleanup actions when they are no longer referenced from within R. This only makes sense for objects that are never copied on assignment, hence the restriction to environments and external pointers.

Inter alia, it provides a way to program code to be run at the end of an R session without manipulating .Last. For use in a package, it is often a good idea to set a finalizer on an object in the namespace: then it will be called at the end of the session, or soon after the namespace is unloaded if that is done during the session.

Value

NULL.

Note

R's interpreter is not re-entrant and the finalizer could be run in the middle of a computation. So there are many functions which it is potentially unsafe to call from f: one example which caused trouble is options. As from R 3.0.3 finalizers are scheduled at garbage collection but only run at a relatively safe time thereafter.

See Also

gc and Memory for garbage collection and memory management.

Examples

1
2
3
4
f <- function(e) print("cleaning....")
g <- function(x){ e <- environment(); reg.finalizer(e, f) }
g()
invisible(gc()) # trigger cleanup

Want to suggest features or report bugs for rdrr.io? Use the GitHub issue tracker.