Décio Luiz Gazzoni Filho
decio at decpp.net
Thu Jan 12 15:49:09 CET 2012
On Jan 11, 2012, at 12:54 PM, Slava Feshchenko wrote:
> I am building a class (called Money) for handling monetary values and use
> GNU MP as a back end for the calculations.
While others have helped you solve your problem with GMP, I am curious what kind of monetary value you would deal with that would be so large as to require more than a 64-bit integer (which should be available in any modern development environment). Even losing a bit to the sign, you can represent positive/negative values over 90 million billion dollars (or whatever your currency).
Using a primitive data type would be much easier and faster than using GMP.
> I can't seem to be able to
> overload operator+. I want very straight forward behavior:
> Money a;
> Money b;
> Money c;
> .... (set a and b to some values)
> c = a + b; //this should set c to the sum of a and b and leave a and b
> The Money class has a private data member declared as follows:
> mpz_t monetaryUnit;
> which maintains the amount of money in cents. So operator+ would be summing
> the values maintained in this variable and assigning it to c.monetaryUnit.
> I already overloaded operator= and it works as expected. The Money class
> has a constructor which calls mpz_init(monetaryUnit) and a destructor,
> which calls mpz_clear(monetaryUnit);
> 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;
> In debug mode, this seems to work until the return statement. The code
> correctly sums the values and assign the result to temp.monetaryUnit; Then
> after the return statement, the destructor is called for the object temp,
> which calls mpz_clear(monetaryUnit). After this call, the value in
> temp.monetaryUnit is something ridiculous like 123198732346827429374
> (instead of the sum of a and b). And this is the value that gets assigned
> to c in the end. What am I missing? What's wrong with my destructor if
> that's where the issue is? Please help!!
> If you need more details on the implementation, please let me know. Also
> note that I typed the code above right in the email, and not copied from
> the actual source code... so please ignore any syntax issues.
> gmp-discuss mailing list
> gmp-discuss at gmplib.org
More information about the gmp-discuss