更改 R6 中的克隆行为 类

Changing cloning behavior in R6 classes

假设我有一个 R6 class,其中一个元素是指向某个 C++ 对象的外部指针。

所以我有这样的东西:

myClass <- R6::R6Class(
  "myClass", 
  public = list(
    xp = NULL,
    initialize = function(x) {
      self$xp = cpp_fun_that_returns_a_pointer(x)
    }
  )
)

如果我使用 myclass$clone(),它仍将指向相同的 myclass$xp。如果我执行 myclass$clone(deep = TRUE) 也会发生这种情况,因为它不知道如何在 C++ 端进行克隆。

在这种情况下,我可以使用自定义 deep_clone 方法...

但是因为在我的用例中,克隆 class 而不 深度克隆 总是错误的,我想知道是否可以改变行为clone 直接。

我只是尝试创建一个 clone() 方法,但 R6 不允许这样做。

Error in R6::R6Class("tensor", cloneable = FALSE, private = list(xp = NULL),  : 
  Cannot add a member with reserved name 'clone'.

如果您使用 cloneable = FALSE,您可以定义自定义 clone() 方法。我不确定你用 XPtrs 做了什么,所以我将演示一个稍微简单的例子:

# Set up the R6 class, making sure to set cloneable to FALSE
myClass <- R6::R6Class(
    "myClass", 
    public = list(
        xp = NULL,
        initialize = function(x = 1:3) {
            self$xp = x
        }
    ),
    cloneable = FALSE
)
# Set the clone method
myClass$set("public", "clone", function() {
    print("This is a custom clone method!") # Test print statement
    myClass$new(self$xp)
})
# Make a new myClass object
a <- myClass$new(x = 4:6)
# Examine it
a
#> <myClass>
#>   Public:
#>     clone: function () 
#>     initialize: function (x = 1:3) 
#>     xp: 4 5 6
# Clone it
b <- a$clone()
#> [1] "This is a custom clone method!"
# We see the test print statement was printed!
# Let's check out b:
b
#> <myClass>
#>   Public:
#>     clone: function () 
#>     initialize: function (x = 1:3) 
#>     xp: 4 5 6

reprex package (v0.2.1)

于 2019-02-05 创建