Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Register finalizers for cloned objects #180

Merged
merged 3 commits into from Feb 14, 2019
Merged
Changes from 1 commit
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

Register finalizers for cloned objects

  • Loading branch information...
wch committed Feb 14, 2019
commit 0735eae60c4061760b81730bf853c0683f865811
@@ -323,6 +323,25 @@ generator_funs$clone_method <- function(deep = FALSE) {
lockEnvironment(new_1_private)
}

# Finalize --------------------------------------------------------
if (is.function(.subset2(new_1_binding, "finalize"))) {
# This wraps the user's `finalize` method. The user's finalize method
# typically does not have an `e` argument, so the wrapper needs to consume
# the `e` argument.
finalizer_wrapper <- function(e) {
.subset2(e, "finalize")()
}
# Reassign the wrapper's environment so that it does not capture the current
# environment and prevent objects from getting GC'd.
environment(finalizer_wrapper) <- baseenv()

reg.finalizer(
new_1_binding,
finalizer_wrapper,
onexit = TRUE
)
}

class(new_1_binding) <- class(old_1_binding)

new_1_binding
@@ -801,3 +801,85 @@ test_that("Cloning with functions that are not methods", {
expect_identical(b3$f(), 1)
expect_identical(b3$g(), 2)
})


test_that("Finalizers run on cloned objects", {
sum <- 0
C1 <- R6Class("C1",
public = list(
x = 1,
finalize = function() sum <<- sum + self$x
)
)

a <- C1$new()
b <- a$clone()
b$x <- 10

rm(b)
gc()
expect_identical(sum, 10)
rm(a)
gc()
expect_identical(sum, 11)

# With inherited finalize method
sum <- 0
C2 <- R6Class("C2", inherit = C1)

a <- C2$new()
b <- a$clone()
b$x <- 10

rm(b)
gc()
expect_identical(sum, 10)
rm(a)
gc()
expect_identical(sum, 11)


# With overridden finalize method
sum <- 0
C3 <- R6Class("C3",
inherit = C1,
public = list(
finalize = function() sum <<- sum + 2*self$x
)
)

a <- C3$new()
b <- a$clone()
b$x <- 10

rm(b)
gc()
expect_identical(sum, 20)
rm(a)
gc()
expect_identical(sum, 22)


# With overridden finalize method which calls super$finalize
sum <- 0
C4 <- R6Class("C4",
inherit = C1,
public = list(
finalize = function() {
super$finalize()
sum <<- sum + 2*self$x
}
)
)

a <- C4$new()
b <- a$clone()
b$x <- 10

rm(b)
gc()
expect_identical(sum, 30)
rm(a)
gc()
expect_identical(sum, 33)
})
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.