Overloading the assignment operator, right now!
Hasan Aljudy
hasan.aljudy at gmail.com
Sat Sep 16 13:29:05 PDT 2006
pragma wrote:
> Hasan Aljudy wrote:
>>
>> I vote:
>> No for copy operators.
>> Specially no for the ugly and cumbersome-to-type := operator.
>>
>> Yes for auto-generated copy methods/properties. (both deep and shallow)
>>
>> T x = b.dup.deep;
>> T y = b.dup.shallow;
>
> The only problem with this is that you can't have a compiler-generated
> deep copy without taking on some serious consequences and/or risks. IMO,
> that's too much effort for a compiler author, for a feature that is so
> limited in use and scope.
>
> Take this guy for example:
>
> class TreeNode{
> TreeNode parent;
> TreeNode[] children;
> }
>
> What about cyclic references in networks of objects (.parent in above)?
> You'd have to have some kind of monitor that keeps track of all the
> references consumed by the dup.deep() process, just to avoid cycles.
> Either it's an Object field that flags its status during a dup() or a
> massive array/map that keeps log of every object touched - either one
> can amount to some very serious space/time overhead.
>
> A stub deep copy, one that lives on Object, isn't possible either since
> D doesn't have the reflection mojo to pull it off. Even if it did,
> would you really want to generate a deep copy of an object network
> completely via reflection? It'd be painfully slow.
>
> Invariably, a custom-coded clone() or dup() of some kind that allows for
> deep copying on request is the best approach - take a look at how other
> languages (e.g. Java) shy away from implementing a deep copy directly
> into the language.
>
> class TreeNode{
> TreeNode parent;
> TreeNode[] children;
>
> TreeNode clone(TreeNode copyParent){
> TreeNode copy = new TreeNode();
> foreach(child; this.children){
> copy.children ~= child.clone(copy);
> }
> copy.parent = copyParent;
> return copy;
> }
> }
>
> What's wrong with doing things like this?
I actually never thought about the problem. Thanks for clearing things out.
>
> Now, I do think that providing a shallow-copy, dup(), as a member of
> Object is a no-brainer. You can easily do this at the binary level via
> memcopy with little to no effort, and no real side-effects. Plus it
> would make the current schism between objects and arrays a little less
> obvious (that is, make templates easier to code).
More information about the Digitalmars-d
mailing list