Language | integer | string | list/array | struct/object |
---|---|---|---|---|
C++ | I | D | D | D |
PHP | I | D | D | D |
Perl | I | D(1) | D | S |
Tcl | I | D? | D? | ? |
Python | I | I | S | S |
Java | I | I | S | S |
Javascript | I | I | S | S |
C# | I | I | S | D/S |
C | I | S,C | S | D |
Smalltalk | I | S,C | S | S |
Common Lisp | I | S,C | S | S |
OCaml | I | S | I/S | S |
Scheme | I | S | S | S |
Ruby | I | S | S | S |
Point *p2; p2 = p; // shallow copy *p2 = *p; // deep copy char *s2; s2 = s; // shallow copy strcpy(s2, s); // deep copyWhen you deep copy a value, it breaks any sharing it has.
Languages using deep copy by default always have a special way to get a shallow copy:
Languages using shallow copy by default sometimes have a way to get deep copy: copy in Smalltalk, Clone in C#, copy.copy in Python... (more, search "object cloning")
Deep or shallow copying have the same result for immutable values.
In C, Smalltalk and Common Lisp, "hello" is a constant value. If you try to modify it, you get a runtime error.
Ruby and OCaml don't have readonly strings, all strings are mutable:
# let f () = "hello" in (f()).[0] <- 'H' ; f();; - : string = "Hello"
Language | Code | Runtime Result |
---|---|---|
C | "hello"[0] = 'H'; | segmentation fault |
Smalltalk | 'hello' at: 1 put: $H | object is read-only |
Common Lisp | (setf (aref "hello" 0) #\H) | Attempt to modify a read-only string |
Scheme | (string-set! "hello" 0 #\H) | |
OCaml | "hello".[0] <- 'H' | |
Ruby | "hello"[0] = "H" | |
Perl | "hello" =~ s/h/H/ | Can't modify constant item |
i = 1 j = i j = j + 1 |
behaving alike this C++ code | int *i = new int(1); int *j = i; *j = *j + 1; |
This is really counter-intuitive ; no programming language have this behaviour.
[1] The address-of operator of Perl and C are different from the "ref" reference constructor of SML and OCaml. In Perl and C, it allows sharing the existing value, whereas ML's "ref" introduces sharing.
int i = 1; int *p = &i; *p = *p + 1;i is modified |
let i = 1 in let p = ref i in p := !p + 1i is not modified |
[2] To be precise "++" is not defined in Ruby. Some explanation about this.
Release: $Id$