Q:

creating a deep copy of a Reference Class: doesn't work on list fields?

I am trying to copy an instance of a reference class (foo) which contains a list field. The list field contains instances of another class (bar). When copying the foo instance using the $copy() method the instances of the lists aren't copied and keep referring to the same object. The code below illustrates the problem. Is there a way around this? How can I do a true deep copy?
bar<-setRefClass("bar", fields = list(name = "character"))
foo<-setRefClass("foo", fields = list(tcp_vector = "list"))

x1<-foo()
x1$tcp_vector <- list(bar(name = "test1"))

x1$tcp_vector[[1]]$name # equals "test1"

x2 <- x1$copy()

x2$tcp_vector[[1]]$name # equals "test1"

x2$tcp_vector[[1]]$name <- "test2"  # set to "test2"

x2$tcp_vector[[1]]$name # equals "test2"

x1$tcp_vector[[1]]$name # also equals "test2"??

A:

The copy method actually copies only ReferenceClass objects. Your foo class has just one field which is a list, and "normal" fields are not copied. This works:
bar<-setRefClass("bar", fields = list(name = "character"))
foo<-setRefClass("foo", fields = list(tcp_vector = "bar"))
x1<-foo()
x1$tcp_vector <- bar(name = "test1")
x1$tcp_vector$name # equals "test1"
x2 <- x1$copy()

x2$tcp_vector$name # equals "test1"

x2$tcp_vector$name <- "test2"  # set to "test2"

x2$tcp_vector$name # equals "test2"
x1$tcp_vector$name # equals "test"

See the help ?setRefClass for details. If you want to keep the foo class defined as in the OP, I guess you have to manually copy any bar object before creating a copy of x1.

