Overloading the assignment operator, right now!

Kristian kjkilpi at gmail.com
Sat Sep 23 04:01:32 PDT 2006


On Sat, 23 Sep 2006 01:03:25 +0300, Bruno Medeiros  
<brunodomedeiros+spam at com.gmail> wrote:
> 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.
>>
>
> I don't think you cave have a compiler-generated deep copy, *at all*. At  
> least for the proper notion of "deep copy".
> When one speaks of a clone method, or of a "deep copy", what one means  
> (or at least *should* mean), is a copy of the "abstract state" of the  
> object. A *conceptual* copy of the the object.
[snip]


I agree. The compiler cannot know the abstract states of objects. Human  
can make very good assumptions or guesses, but I think that one still have  
to look at the documentation to be 100% sure, in a general case at least.

So, you have to implement clone methods by yourself, which can be a lot of  
work. I guess this is one of the reasons that objects in D are reference  
types. Of course, nothing prevents you to implement clone functions by  
yourself, but used in common 'calculations', it's cumbersome. Well,  
sometimes you could use structs instead of classes, but not always. One  
solution could indeed be a copy operator (which should be easy to type;  
suggestions?). The copy operator would simply call the clone method if it  
exists.

But, copying value types around can be time consuming, though. For  
example, in C++:

class HugeMatrix;

HugeMatrix func() {
     HugeMatrix a, b, c, d;
     ...
     d = (a + b) - c;
     ...
     return d;
}

'HugeMatrix' gets copied four times. Using references (as in D):

HugeMatrix func() {
     HugeMatrix a, b, c;
     ...
     d = (a.clone().add(b)).sub(c);
     ...
     return d;
}

copying is done only once. It's efficient, but not pretty.

Of course, one could use lazy copying in C++, but that cannot be  
automatically implemented by the compiler. (Well, I remember reading a  
paper where C++ templates were used in a bizarre way to get rid of  
creating unnecessary temporaries in such calculations... where I put it...)


Could it be possible that the compiler would do the following conversion:

"d = (a + b) - c;"
->
"d = (a.opClone().opAdd(b)).opSub(c);"

'd' would be marked as 'copyable object' in the class declaration, or  
something, so that compiler will know that the 'opClone()' should be  
called in such situations.



More information about the Digitalmars-d mailing list