Is there a destructor in the R reference class?

As a test:

myclass = setRefClass("myclass",
                       fields = list(
                           x = "numeric",
                           y = "numeric"
                       ))


myclass$methods(
    dfunc = function(i) {
        message("In dfunc, I save x and y...")
        obj = .self
        base::save(obj, file="/tmp/obj.rda")
    }
    )

myclass$methods(
    print = function() {
            if (.self$x > 10) {
                stop("x is too large!")
            }
    message(paste("x: ", .self$x))
    message(paste("y: ", .self$y))
    }
    )

myclass$methods(
    initialize = function(x=NULL, y=NULL, obj=NULL) {
        if(is.null(obj)) {
            .self$x = x
            .self$y = y
        }
        else {
            .self$x = obj$x
            .self$y = obj$y
        }
    }
)


myclass$methods(
finalize = function() {
    message("I am finalizing this thing...")
}
)

      

Then try to create and delete the object:

u = myclass(15, 6)
u$print()
rm(u)

      

The finalize function is not called at all ...

+3


source to share


1 answer


When you call rm

, you just remove the object reference from the environment, but you don't destroy the element.
It is the job of the garbage collector to automatically destroy objects when they have a reference link (as in this case). Anyway, the garbage collector is triggered by some special events (like too much memory used, etc.), so it is not called automatically when called rm

(it will probably be called later).

Anyway, you can force the garbage collector, even if it is usually discouraged by calling gc()

.



u = myclass(15, 6)
rm(u)
gc()

# > I am finalizing this thing...

      

As you can see by running the above code your finalize method is actually called after gc()

+5


source







All Articles