Operator overloading -- lets collect some use cases
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Tue Dec 30 11:41:00 PST 2008
Denis Koroskin wrote:
> On Tue, 30 Dec 2008 22:26:19 +0300, Andrei Alexandrescu
> <SeeWebsiteForEmail at erdani.org> wrote:
>
>> Don wrote:
>>> Frits van Bommel wrote:
>>>> Don wrote:
>>>>> Frits van Bommel wrote:
>>>>>> Don wrote:
>>>>>>> A straightforward first step would be to state in the spec that
>>>>>>> "the compiler is entitled to assume that X+=Y yields the same
>>>>>>> result as X=X+Y"
>>>>>>
>>>>>> That doesn't hold for reference types, does it?
>>>>>
>>>>> I thought it does? Got any counter examples?
>>>>
>>>> For any class type, with += modifying the object and + returning a
>>>> new one:
>>> Sure, you can do it (behaviour inherited from C++), but is that
>>> _EVER_ a good idea? I can't think of any cases where that's anything
>>> other than a bug-breeder.
>>>
>>>> You can't just arbitrarily substitute between these two.
>>> I'm still looking for a use case where that substitution doesn't make
>>> sense. No-one has yet come up with such a use case. I postulate that
>>> it doesn't exist.
>>
>> 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.
>>
>> Andrei
>
> It was suggested 2 posts up the thread. I believe Don is looking for a
> use case where given
>
> a1 = a + b;
>
> a2 = a;
> a2 += b;
>
> the following check intentionally fails:
>
> assert(a1 == a2); // not "a1 is a2"
>
> He postulates that none exists.
Well then the post situated 2 posts up the thread was right because "is"
vs. "==" is a red herring. For class types the two are not equivalent.
The following two could be equivalent assuming correct definitions:
a1 = a + b;
and
a2 = deepCopy(a);
a2 += b;
This also suggests that it may sometimes be inefficient to define + in
terms of += (which is a tad counterintuitive in C++ circles).
Andrei
More information about the Digitalmars-d
mailing list