string sharing (possible bug?)
Tim Olson
tim at jumpnet.com
Wed Dec 9 15:59:26 UTC 1998
>I realize that in Smalltalk variables *point* to objects. But in the
>above code, I assigned the constant string 'hello' to "a" and "b"
>separately -- I didn't assign a to b -- yet they still obviously point
>to the same object. Is this what is supposed to happen, or is this
>some copy-on-write string sharing scheme gone awry?
Yes, it is supposed to happen this way. The compiler "unifies" all equal
literal value uses within a method. Look at it this way:
| a b c|
c := 'hello'.
a := c.
b := c.
>If this is the
>correct behaviour, then I suppose a good Smalltalk programming rule
>would be, "don't modify an array or string object that has been
>initialized from a constant", because otherwise you may inadvertantly
>affect some other part of your program which also has a variable
>initialized from an identical constant.
Right (although literals are shared at the method-level, not
system-wide). If you want to modify a value from a base literal, you
should use "copy", e.g.:
a := 'hello' copy.
a at: 2 put: $i.
What should be done here is to make literals immutable, and cause an
error when modification is attempted, rather than silently modifying the
literal. I seem to remember someone posting an immutable-collection
class awhile back, along with modifications to the compiler to create
immutable strings and vectors.
-- tim
More information about the Squeak-dev
mailing list
|