The following code prints "false":
a := 'aaa'.
b := a deepCopy.
Transcript show: (a == b).
I do expect this behavior and my explanation to this would be that deepCopy returns a new object "b" that is a completely different object than "a" and since operator "==" compares by reference the result is "false". Is that correct?
However, I do not understand why the following code produces "true":
a := 'aaa'.
b := 'aaa'.
Transcript show: (a == b).
Here we made two assignments to two different objects, "a" and "b", and there shouldn't be any relation between them except the fact that they contain the same value. But if operator "==" compares by reference and not by value, why is the result of this comparison "true"?
The same misconception in both cases is that the question is not "what happens?", but "what is guaranteed?". The key is that there is no guarantee that 'aaa' == 'aaa'
, but the compiler and VM are free to do things that way. The same seems true for the case of copying; since strings are immutable, I guess there's nothing to say that copying a string couldn't return the same object!
In your first example, as usual, the best teacher is the image. #deepCopy
delegates to #shallowCopy
, which at some point evaluates class basicNew: index
, and copies the characters into the new object. So, this particular implementation will always create a new object.