Who deletes the copied instance in + operator ? (c++)

c++, copy, memory, operator-keyword, variable-assignment

Solution

Under the circumstances, I'd probably consider something like:

MyClass MyClass::operator+(MyClass other) { 
     other += *this;
     return other;
}

Dave Abrahams wrote an article a while back explaining how this works and why this kind of code is usually quite efficient even though it initially seems like it shouldn't be.

Edit (thank you MSalters): Yes, this does assume/depend upon the commutative property holding for `MyClass`. If `a+b != b+a`, then the original code is what you want (most of the same reasoning applies).

Problem

I searched how to implement + operator properly all over the internet and all the results i found do the following steps : ``` const MyClass MyClass::operator+(const MyClass &other) const { MyClass result = *this; // Make a copy of myself. Same as MyClass result(*this); result += other; // Use += to add other to the copy. return result; // All done! } ``` I have few questions about this "process" : Isn't that stupid to implement + operator this way, it calls the assignment operator(which copies the class) in the first line and then the copy constructor in the return (which also copies the class , due to the fact that the return is by value, so it destroys the first copy and creates a new one.. which is frankly not really smart ... ) When i write a=b+c, the b+c part creates a new copy of the class, then the 'a=' part copies the copy to himself. who deletes the copy that b+c created ? Is there a better way to implement + operator without coping the class twice, and also without any memory issues ? thanks in advance

Original source