Operator overloading -- lets collect some use cases

Don nospam at nospam.com
Thu Jan 1 10:42:59 PST 2009


Andrei Alexandrescu wrote:
> Frits van Bommel wrote:
>> Don wrote:
>>> Andrei Alexandrescu wrote:
>>>> Well I forgot whether BigInt is a class, is it? Anyhow, suppose it 
>>>> *is* a class and as such has reference semantics. Then a += b 
>>>> modifies an object in-situ, whereas a = a + b creates a whole new 
>>>> object and happens to bind a to that new object.
>>>
>>> You're right, though BigInt is not a class. I have, though, seen a 
>>> BigIntRef class (in Diemos, I think) which behaved in that way. 
>>> AFAIK, the reason it existed was that the only way you can enforce 
>>> value semantics in D1 is via copy-on-write, which results in many 
>>> unnecessary heap allocations and copies.
>>> So Fritz is correct, it could not be enforced for reference types.
>>
>> First of all, please note that I'm not German so my name ends with an 
>> 's', not a 'z'.
>>
>>> The question then is, when are reference semantics desired for an 
>>> object with arithmetical operator overloading?
>>>
>>> For matrix slices, maybe? But even then I'm not certain you'd want to 
>>> allow X=X+Y; you'd probably want to use X[]=X[]+Y[].
>>
>> I never said it'd be useful to use arithmetic ops with classes. In 
>> fact, my suggestion was to just only apply these transformations to 
>> structs since they probably wouldn't be very useful for classes anyway.
> 
> The problem is that even structs may have reference semantics.
> 
> Andrei
Yes. Interestingly, it's relatively difficult to give a struct correct 
reference semantics.
For example, you might implement a bigint class as a struct X with a 
dynamic array containing the actual number. If you naively use in-place 
operations on this array, you quickly run into problems since eg X+=1 
will cause a reallocation if and only if X=0xFFFFFFFF....
Which gives you reference semantics most of the time, but occasionally 
gives value semantics instead. I believe this can only be solved with 
another layer of indirection.

As far as I can tell, reference semantics are only possible if the 
struct contains a pointer to something with value semantics, for example 
, a struct, a class, or a fixed-length array; or else to another pointer.

I had once thought that reference semantics may be sometimes desirable 
for performance reasons, but it seems that it is more likely that they 
are less efficient.




More information about the Digitalmars-d mailing list