Operator overloading -- lets collect some use cases
Don
nospam at nospam.com
Wed Dec 31 07:02:39 PST 2008
Stewart Gordon wrote:
> Don wrote:
>> Andrei Alexandrescu wrote:
> <snip>
>>> 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.
>
> Assuming that BigInt is mutable.
>
>> 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.
>> 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[].
>
> They would probably do different things:
Yes.
> - assigning to X would reassign the reference that is X
There's no problem with X=Y. But X=X+Y would imply creating a new piece
of matrix, and assigning X to it. I'm not sure that's an operation which
you would want. I guess D strings work that way, though.
> - assigning to X[] would fill X in-place.
In-place operations are straightforward: they are definitely useful.
> Stewart.
More information about the Digitalmars-d
mailing list