Returning a new object on overloaded operators seems the only thing to do. Right?
- If you have a class (X) that contains a large buffer
- Part of the buffer contains content, rest is free.
- You have overloaded the binary + operator to merge two objects (of same type) by creating a new object containing the appended contents of both operands.
In other words:
z = x + y // z is a new object containing the appended data from x and y.
This is obviously good because we don't want to mangle x or y during the operation. However, C# language specs 7.2.2 say:
When a binary operator is overloaded, the corresponding assignment operator (if any) is also implicitly overloaded.
this means that:
x += y; // will create a new x, copy contents of old x merged with y
// and the old x will be garbage collected at some point
This is painful, because it could be much faster to just copy the contents of y in the free portion of x. That way we don't copy a large object and leave a mess for the nice garbage collector person.
I realize that this could be done with a simple x.Add(y). I am curious if there is a way to do it using operators. for example to figure out we are inside the assignment operator and perform the optimized routine.