如何理解#dup和#clone对引用其他对象的对象进行操作? [英] How to understand the #dup and #clone operate on objects which referencing other objects?
问题描述
在 ruby
的文档中,我不确定 ...但不是它们引用的对象的含义 code> rubinus 。
I am not sure about the meaning of "...but not the objects they reference" in both the documantion of ruby
and rubinus
.
在红宝石,其中有 #clone
和的解释#dup
行为说:
产生obj的浅表副本-obj的实例变量为
复制,但不复制它们引用的对象。复制obj的冻结和
污染状态。另请参见Object#dup下的讨论。
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj. See also the discussion under Object#dup.
在鲁比尼乌斯:
复制实例变量,但不递归复制它们引用的对象
。
Copies instance variables, but does not recursively copy the objects they reference. Copies taintedness.
我尝试了以下代码,但是行为超出了我的预期。
I tried out with the following code, but the behavior is out of my expectation.
class Klass
attr_accessor :array
end
s1 = Klass.new
ar = [1, 2, 3]
s1.array = [ar]
s2 = s1.clone
# according to the doc,
# s2.array should be initialized with empty Array
# however the array is recursivley copied too
s2.array.equal? s1.array # true
推荐答案
在Ruby中,所有对象都是参考。看下面的示例:
In Ruby, all objects are references. Take a look at the following example:
class Klass
attr_accessor :a
end
s1 = Klass.new
a = [1,2,3]
s1.a = a
s2 = s1.clone
s1.a.object_id #=> 7344240
s2.a.object_id #=> 7344240
您可以看到两个数组都是同一个对象,并且都是引用到位于堆中某处的数组。在深层副本中,该数组本身将被复制,而新的 s2
将具有其自己的独特数组。
You can see that both of the arrays are the same object, and are both references to the array living somewhere in the heap. In a deep copy, the array itself would have been copied, and the new s2
would have its own, distinct array. The array is not copied, just referenced.
注意:
如果进行深层复制,它的外观如下:
Note: Here's what it looks like if you do a deep copy:
s3 = Marshal.load(Marshal.dump(s1)) #=> #<Klass:0x00000000bf1350 @a=[1, 2, 3, 4], @bork=4>
s3.a << 5 #=> [1, 2, 3, 4, 5]
s1 #=> #<Klass:0x00000000e21418 @a=[1, 2, 3, 4], @bork=4>
这篇关于如何理解#dup和#clone对引用其他对象的对象进行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!