Cloning in D
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Mon Sep 6 07:12:43 PDT 2010
On 09/05/2010 10:15 PM, dsimcha wrote:
> I've started playing around with Orange a little to see whether it would meet
> D's cloning needs. IMHO one must-have feature for proper cloning that truly
> "just works" is full aliasing preservation.
What do you mean by aliasing preservation? I'd think you want no
aliasing between the clone and the original. (Perhaps you mean that the
object graph of the clone and original look the same?)
First off, let's see what cloning methods we have:
1. We know how to clone built-in types except pointers. (Arrays are
cloned by duplicating the array proper and cloning each element.)
2. Structs can be cloned with either this(this) or by cloning each of
their fields.
3. For classes we can define a conventional method/interface, e.g.
clone/Cloneable.
Now, given some arbitrary value v, we know how to obtain a clone of it
by applying the rules above. The problem is, there are two opaque calls:
this(this) for structs and obj.clone() for classes. If improperly
implemented, the whole thing comes unglued. The problem is the standard
library (and others) must rely on correct deep cloning without being
able to check it.
Although it's difficult to implement deep cloning, it's relatively easy
to _verify_ it. So I'm thinking, a generic deepdup() routine would apply
cloning per the rules above and then would verify that opaque calls
obj.clone() and this(this) did not produce any aliasing.
Bottom line, this clarifies we need dynamic field information for
classes. Otherwise we wouldn't be able to "see" through polymorphism.
Andrei
More information about the Digitalmars-d
mailing list