Operator "+=" overloading for class?

Steven Schveighoffer schveiguy at gmail.com
Wed Dec 20 02:56:24 UTC 2023


On Monday, 18 December 2023 at 14:38:14 UTC, Ki Rill wrote:
>> your code just return result value,
>> but it should not return but save result to "this"
>> see example at 
>> https://dlang.org/spec/operatoroverloading.html#index_op_assignment
>
> I get an error, but don't understand why.
> ```d
> auto opOpAssign(string op)(Value rhs)
> {
>     this = this + rhs;
>     return this;
> }
>
> // Error: `this` is not an lvalue and cannot be modified
> ```

Assigning an object is like copying a pointer. You may think you 
can try overloading the assignment, but it is 
[forbidden](https://dlang.org/spec/operatoroverloading.html#assignment):

```
However for class types, identity assignment is not allowed. All 
class types have reference semantics, so identity assignment by 
default rebinds the left-hand-side to the argument at the right, 
and this is not overridable.
```

But you aren't trying to do this.

Instead you are trying to reassign the `this` reference, which is 
a local (and also forbidden). Think about it a second, your `this 
+ rhs` is going to allocate a *new* object. Then if the 
assignment to the local `this` parameter succeeded, what happens 
outside the member function? The true reference that is calling 
this will not be updated!

The only way to do this I can see is to reimplement for op=, or 
maybe perform the operation and swap the guts out.

-Steve


More information about the Digitalmars-d-learn mailing list