复制对象

类

new_shape <- function(line_count, name) {
  structure(list(line_count = line_count,
                 name = name),
            class = "Shape")
}

square <- new_shape(4, "Square")
# S3: assignment already gives a copy
square_copy <- square
square$name <- "Box"
# square_copy$name = Square

RefShape <- setRefClass("RefShape",
  fields = list(line_count = "numeric",
                name = "character"))

ref_square <- RefShape$new(line_count = 4,
                           name = "Square")
# A reference object is copied with copy()
ref_copy <- ref_square$copy()
ref_square$name <- "Box"
# ref_copy$name = Square

cat("square_copy$name =", square_copy$name, "\n")
cat("ref_copy$name =", ref_copy$name, "\n")