【发布时间】:2016-08-30 13:07:17
【问题描述】:
我真的不明白浅拷贝和深拷贝的区别。 Ruby 的#dup 在我测试时似乎创建了一个深拷贝。
文档说:
Produces a shallow copy of obj---the instance variables of obj are
copied, but not the objects they reference.
但是当我对此进行测试时,它似乎改变了它们引用的对象。
class Klass
attr_accessor :name
end
a = Klass.new
a.name = "John"
b = a.dup
b.name = "Sue"
puts a.name # John
当@name 是objects they reference 之一时,为什么这里的浅拷贝就足够了?
需要深拷贝的最简单示例是什么?
【问题讨论】:
标签: ruby deep-copy shallow-copy