qed
qed

Reputation: 23114

Is there a destructor in R reference class?

Just 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 remove an object:

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

The finalize function is not called at all...

Upvotes: 4

Views: 1198

Answers (1)

digEmAll
digEmAll

Reputation: 57210

When you call rm you just remove the object reference from the enviroment, but you don't destroy the element.
That is the work of the garbage collector that is designed to automatically destroy objects when they have nomore reference (like in this case). Anyway, the garbage collector is triggered by some special events (e.g. too much memory used etc.), so it is not automatically invoked when you call rm (it will be probably called later later).

Anyway, you can force the garbage collector, even if this 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 indeed called after gc()

Upvotes: 7

Related Questions