2014-08-28 1 views
1

목록 필드가 들어있는 참조 클래스 (foo)의 인스턴스를 복사하려고합니다. 목록 필드에는 다른 클래스 (bar)의 인스턴스가 포함됩니다. $copy() 메서드를 사용하여 foo 인스턴스를 복사 할 때 목록의 인스턴스는 복사되지 않고 동일한 개체를 계속 참조합니다. 아래 코드는 문제를 보여줍니다. 이 문제를 해결할 방법이 있습니까? 진정한 깊은 사본을 작성하려면 어떻게해야합니까?참조 클래스의 전체 복사본을 만드는 중 : 목록 필드에서 작동하지 않습니까?

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"?? 
+0

ref 클래스에 대한 단서가없고 copy가 자동으로 올바르게 구현되었지만'copy = new ("MicroPlate")와 같은 것으로 덮어 쓸 수 있습니다. listOldVars = ls (envir = self @ .data, all.names = T) for (listOldVars) { copy @ .data [[i]] = 자기 @. 데이터 [} return (copy)' – phonixor

답변

1

실제적으로 copy 방법 만 복사 ReferenceClass 객체. foo 클래스에는 list 인 필드가 하나만 있으며 "일반"필드는 ​​복사되지 않습니다. 작동 방식 :

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" 

자세한 내용은 도움말 ?setRefClass을 참조하십시오. OP 에서처럼 foo 클래스를 유지하려면 x1 복사본을 만들기 전에 bar 개체를 수동으로 복사해야합니다.

관련 문제