如何理解#dup和#clone对引用其他对象的对象进行操作?

编程入门 行业动态 更新时间:2024-10-24 18:19:24
本文介绍了如何理解#dup和#clone对引用其他对象的对象进行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 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对引用其他对象的对象进行操作?

本文发布于:2023-11-02 13:53:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   操作   dup   clone

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!