4

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...

qed
  • 22,298
  • 21
  • 125
  • 196

1 Answers1

6

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()

digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • Thanks. Another interesting thing, if I set x as read only by myclass$lock("x"), then the attempt to set a new value for x will also invoke finalize(), why is that? – qed Aug 13 '14 at 15:15
  • @qed: interesting, can you post an example of how you're setting x after locking it ? – digEmAll Aug 13 '14 at 15:23
  • Oh, sorry, canot repeat it anymore, must have been an accident, the GC happened to be at work when I tried that, I guess. – qed Aug 13 '14 at 15:28
  • @qed: I see, but I'm still interested in how you set 'x' after making it readonly... it should raise an error... – digEmAll Aug 13 '14 at 15:40
  • Yeah, it did raise an error. I just did something like obj$x = 222. – qed Aug 14 '14 at 10:51