What is the state of opAssign?

Nathan Reed nathaniel.reed at gmail.com
Sat Oct 20 20:25:05 PDT 2007


BCS wrote:
> Reply to Nathan,
> 
>> BCS wrote:
>>
>>> would this work
>>>
>>> class C
>>> {
>>> static C opImplicitCastFrom(real r){...}
>>> C opAssign(B b){...}
>>> }
>>> class B {}
>>>
>>> auto b = new B;
>>> real r = 5;
>>> r = b;  //opImplicitCastFrom(r).opAssign(b);
>> I'd be very suspicious of using the return value of a function as an
>> lvalue!
>>
>> What is the value in 'r' after this code has executed??
>>
>> Thanks,
>> Nathan Reed
> 
> Depends on what I'm doing with it. In the simple case, the above would 
> work as expected but would be able to also do something with r.
> 
> struct C
> {
>  real* rr;
>  static C opImplicitCastFrom(ref real r)
>  {
>    C ret;
>    ret.rr = & r;
>    return ret;
>  }
>  C opAssign(B b)
>  {
>    //... uses rr
>    //*rr = cast(real) b;
>  }
> }
> class B {}
> 
> 

Frankly, I think this is a very bad idea.  With the usual semantics of 
assignment are it *doesn't* depend on the current value of the lhs. 
Overloading an operator such that its semantics violates the assumptions 
programmers normally make about it is never good imho.  This is why D 
doesn't allow commutative operators to be overloaded as non-commutative, 
etc...

Thanks,
Nathan Reed


More information about the Digitalmars-d-learn mailing list