Skip to content

Functions are not properly GC'd #154

Closed
@wch

Description

@wch

Here's a normal case of a function being GC'd. (I'm creating it in a local environment so that I can register a finalizer.)

f <- local({
  e <- environment()
  reg.finalizer(e, function(e) message(format(e), " finalized\n"))
  function() {
    message("Environment is ", format(e), "\n")
  }
})

f()
#> Environment is <environment: 0x7fad6689cdb0>

rm(f); invisible(gc())
#> <environment: 0x7fad6689cdb0> finalized

With cpp11, if I pass f to a C++ function as a cpp11::function object, it does NOT get GC'd:

library(cpp11)
cpp_function('void invoke(function fn) {
  fn();
}')

f <- local({
  e <- environment()
  reg.finalizer(e, function(e) message(format(e), " finalized\n"))
  function() {
    message("Environment is ", format(e), "\n")
  }
})

invoke(f)
#> Environment is <environment: 0x7fad67438b20>

rm(f); invisible(gc())
# (No output)
invisible(gc())
# (No output)

However, if I call invoke() on another function, it seems to free up the reference to the previous function that was passed to invoke(), and allows it to be GC'd:

invoke(function() 1)
invisible(gc())
#> <environment: 0x7fad67438b20> finalized

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions