| Chris Page 2004-06-22, 11:20 pm |
| Recently there was a discussion in the #dylan IRC channel on
freenode.net about object copying in Dylan.
Someone asked how to copy objects as in C++, where assignment is a
copying operation and when the destination is a class (or struct) the
compiler can automatically generate a simple bitwise copy of its data
members.
There are several points to be made:
1. In Dylan, assignment to a binding (a constant, variable, or function
parameter) with ':=' does not copy or construct an object, it merely
makes that binding refer to the source object. Compared to C++, it is as
if every variable were a pointer to a heap-allocated object, so
assignment merely copies the pointer.
2. Since Dylan always uses reference semantics (every binding is like a
pointer to an object), there is no implicit copying of objects as there
is in C++. e.g., C++ copies objects to create temporaries while
evaluating an expression. In contrast, objects are only copied
explicitly in Dylan, and copying is performed much more rarely than in
C++.
3. Copying is generally accomplished either by calling shallow-copy() or
simply creating a new object with make() and passing in initial values
taken from a source object.
4. By default, shallow-copy() is only defined for collections. In order
to use it with other classes, you must define a method yourself. There
is no automatic way to copy the slots of a user-defined object. The
justification for this is that copying is not usually as simple as just
copying the bits of each slot. The same is actually true of C++, where
most non-trivial classes require user-defined copy constructors or
operator= member functions to handle copying correctly.
Prompted by this discussion, I did a survey of all the Dylan code in the
Gwydion Dylan CVS repository in ./fundev, ./libraries, and ./src for
definitions and uses of shallow-copy().
As expected, there are relatively few uses and definitions of
shallow-copy(). Important to note is that only two or three
shallow-copy() methods are effectively trivial slot copying.
Furthermore, the one I wrote (back in 1997) may not even be necessary or
desirable. (The one in the FunDev IDE searching code.)
This informal survey confirms that at least in that body of code,
copying objects is not a frequent operation (relatively speaking), and
most implementations of copying require something at least slightly more
complicated than simple slot value copying.
Direct or indirect copying of collections (via choose(),
copy-sequence(), etc.) is more frequent, but copying collections is more
uniform, since all elements are treated more or less the same (as
opposed to copying slots, where there is more variation in how and which
slots get copied.)
--
Chris Page - Software Wrangler - Dylan Pundit
Open Source Dylan: <http://www.gwydiondylan.org/>
Dylan Blogging: <http://homepage.mac.com/chrispage/iblog/>
|