On Sat, 24 Jan 2004 04:30:51 GMT in comp.lang.c++, "Aire"
<ai*****@zoomit.org> was alleged to have written:
To implement the '+' overloading, the type of return value could be either
"Class1" or "Class1&".
Class1& Class1::operator+(const Class1& a, const Class1& b){ }
Class1 Class1::operator+(const Class1& a, const Class1& b){ }
What are the differences implied by the two return types?
Typically, returning a reference from operator+ is a mistake.
In returning a value, the implication is that the value is copied to a
result location arranged for it. This copy may actually be eliminated
if the compiler is able to do so (called the return value optimization.)
In returning a reference, you the programmer must arrange for memory to
store the value, Automatic storage in the called routine cannot be used
for this, since it is deallocated when the function returns before the
value can be used. Dynamic memory creates the problem of when and where
to release it, and static memory causes problems for reentrant routines
and requires saving the value before calling the function again.