operator+ overloading

André Pönitz andre.poenitz at mathematik.tu-chemnitz.de
Wed Jan 11 23:20:52 CET 2012


On Wed, Jan 11, 2012 at 09:54:40AM -0500, Slava Feshchenko wrote:
> [...]
> The broken code for operator+ is as follows:
> 
> Money & Money::operator+(Money &m)
> {
> Money temp;
> mpz_add(temp.monetaryUnit, this->monetaryUnit, m.monetaryUnit);
> return temp;
> }

You are returning a reference to a temporary which will be destroyed when
then function returns. Don't do that. Return a copy. [And make sure your
copy constructor works]

That it appears to work in debug mode is just (bad) luck.

Andre'

PS: You also _pass_ a non-const reference for no good reason, and made
the operator asymmetric by making it a member, instead of a free function.
If you really want to keep it as member, make it at least const.


More information about the gmp-discuss mailing list