[comp.lang.smalltalk] Repost of STV copy methods an explanation

trr@rayssd.ray.com (Terry R. Raymond) (04/12/88)

There have been some questions about my posting about Smalltalk/V
copy methods so I am reposting it and an explaination of what I
have learned since.

I am using Smalltalk/V and would like to know if the following
methods behave the same way in Smalltalk-80.  The methods of
concern are; assignment, shallowCopy and deepCopy.  The expressions
below demonstrate their behavior.  Would somebody who uses
Smalltalk-80 please inform me if the methods behave the same way in
Smalltalk-80.  The expressions were evaluated with "Show it".

Assignment

| a b |
a := #(23 45 78).
b := a.
b at: 1 put: 93.
^a  

The result was  (93 45 78).

Shallow copy

| a b |
a := #(23 45 78).
b := a shallowCopy.
b at: 1 put: 93.
^a

The result was (23 45 78).

| a b |
a := #(23 (45 56) 78).
b := a shallowCopy.
(b at: 2) at: 1 put: 93.
^a
   
The result was (23 (93 56) 78).


Deep Copy

The first example was the same as shallowCopy.

| a b |
a := #(23 (45 56) 78).
b := a deepCopy.
(b at: 2) at: 1 put: 93.
^a
 
The result was (23 (45 56) 78).

| a b |
a := #(23 (45 (56 78) 91) 84).
b := a deepCopy.
((b at: 2) at: 2) at: 1 put: 99.
^a
 
The result was (23 (45 (99 78) 91) 84).

Hans-Martin Mosner replied to this posting and said that all but the last
example behaved properly.  I examined the deepCopy source and
found out why.  A portion of the method source follows.

deepCopy
        "Answer a copy of the receiver with shallow
         copies of each instance variable."
    | copy aClass instanceVars |
code deleted
    aClass isPointers
        ifTrue: [
            1 to: instanceVars + aClass instSize do: [ :index |
                copy instVarAt: index
                    put: (self instVarAt: index) copy]]
        ifFalse: [                               ^^^^ 
            1 to: instanceVars do: [ :index |        
                copy basicAt: index
                    put: (self basicAt: index)]].
    ^copy

Notice the call to "copy" this results in a call to "shallowCopy"
which will not create a new copy of the entire structure.  I changed
the call to "copy" to "deepCopy" so that it now recursively creates a
new structure and it works correctly.
-- 
Terry Raymond
Raytheon Submarine Signal Division; Portsmouth RI; (401)-847-8000 x5597
smart mailer or arpanet: trr@rayssd.ray.com
old dumb mailer or uucp: {cbosgd,gatech,ihnp4,linus!raybed2} !rayssd!trr