views:

46

answers:

2

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.

+2  A: 

I personally like how C# implemented this.

It's more "obvious" that:

x += y;

and

x = x + y;

Should have the same behavior. In C#, this is enforced. With separate overloads, people could abuse the operator and prevent this from acting the same.

The perf difference will be so minimal, and this also makes it easier to implement and maintain, so I strongly prefer the C# approach.

Reed Copsey
You're right, from a formal language perspective, those two should be exactly the same. Though, I'm not sure if there is or should be any way to optimize these scenarios.
MandoMando
A: 

All mathematical binary operators returns a new object. E.g. You wouldn't want 2+3 to alter the value of one of Them to five just because you were adding them. In other words the semantics of the operators in question is very clear and enforced through the specs. If you want something different you'll have to make something different :). And I personaly like it compare to c++ where you Can make overloading such the A=B=C could result in C being deleted, B being unassigned and A equaling any value with no regards to either C or B

Rune FS