shadow copy and deep copy

E

Eva

SGVsbG8sCgp4PVsxLDIsM10KeT14LmR1cAoKdGhpcyBpcyBhIHNoYWRvdyBjb3B5LCBJIGtub3cg
dGhlIHRoZW9yeSBiZWhpbmQgaXQuCgp6PXgKCmlzIHRoaXMgYSBkZWVwIGNvcHk/ICh6IGlzIHRo
ZSBkZWVwIGNvcHkgb2YgeD8pCgpUaGFua3MK
 
A

Adrian Tepes

Eva wrote in post #960269:
Hello,

x=[1,2,3]
y=x.dup

this is a shadow copy, I know the theory behind it.

z=x

is this a deep copy? (z is the deep copy of x?)

Thanks

I don't think it's deep copy.
irb(main):010:0> print z.__id__
137429210=> nil
irb(main):011:0> print x.__id__
137429210=> nil
irb(main):012:0> print y.__id__
137515980=> nil
irb(main):013:0> z.push 4
=> [1, 2, 3, 4]
irb(main):014:0> p x
[1, 2, 3, 4]
=> [1, 2, 3, 4]
 
R

Robert Klemme

2010/11/9 Eva said:
x=[1,2,3]
y=x.dup

this is a shadow copy, I know the theory behind it.

Actually it's called "shallow copy". And what #dup really does
depends on the class so it could even implement a deep copy (although
that is normally not the case). In the case of Array you are correct,
it's a shallow copy.
z=x

is this a deep copy? (z is the deep copy of x?)

No, there is no copy of state at all. This is called "aliasing": now
both z and x point to the same object.

Example for deep copy:

z = Marshal.load(Marshal.dump(x))

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top