swarm-support
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: creating a copy of an object


From: Roger M. Burkhart
Subject: Re: creating a copy of an object
Date: Wed, 4 Feb 1998 09:25:59 -0600

Rick Riolo asks:

> What's the latest ideas about the best way to create a copy
> of an object (without having to write one's own copy method)?
> I have used:
> 
>   id newBug = [[self getZone] copyIVars: self];
> 
> Are there better ways, or reasons not to use the above approach?
> When would the above fail (i.e., give surprising results)?

This code should work fine without surprises, unless your instance
variables point to any allocations that are internal to the object,
in which case you'd have two objects that share private parts.

This is what's often called a "shallow" copy as opposed to a "deep"
copy that copies any internal components along with the surface object.
For simple agents that store all their state in their ivars, a shallow
copy is all you need.  We've avoided making it part of a default copy
message (as the OpenStep library did) to avoid the inadvertent error
when it's not appropriate.  (We don't like creating surprises.)

If you need a deep copy, you should go ahead and code a copy: message,
using the [anObject copy: aZone] form of message we use on other Swarm
objects that support a copy.  Internally, a deep copy method would use
the same initial code fragment as you've got above, followed by
additional copy operations on any components that reassign instance
variables that reference the components.  An example of a shallow copy
method is in the archives someplace, but it's nothing more than your
basic code above inside the method body:

- copy: aZone
{
  return [aZone copyIVars: self];
}

An advantage of the copy: message is that allows allocating the new
object in a different zone (such as a swarm) if it belongs there, which
would be an issue only in larger simulations that use multiple zones or
swarms within the model.

--Roger 


                  ==================================
   Swarm-Support is for discussion of the technical details of the day
   to day usage of Swarm.  For list administration needs (esp.
   [un]subscribing), please send a message to <address@hidden>
   with "help" in the body of the message.
                  ==================================


reply via email to

[Prev in Thread] Current Thread [Next in Thread]