#include <iostream>
using namespace std;
// example low level C code big integer data type
typedef int* mpz_t;
bool check = false;
void mpz_init(mpz_t &x) {
if (check) cout << "initing\n";
x = new int;
*x = 0;
}
void mpz_set(mpz_t &dest, const mpz_t &src) {
if (check) cout << "setting\n";
*dest = *src;
}
void mpz_set_si(mpz_t &dest, const int &val) {
if (check) cout << "setting si\n";
*dest = val;
}
void mpz_add(mpz_t &res, const mpz_t &a, const mpz_t &b) {
*res = (*a) + (*b);
}
void mpz_mul(mpz_t &res, const mpz_t &a, const mpz_t &b) {
*res = (*a) * (*b);
}
/**********************************/
// class with canonical form
class bignum
{
public:
mpz_t value;
public:
bignum() {
mpz_init(value);
}
bignum(int val) {
mpz_init(value);
mpz_set_si(value, val);
}
bignum(const bignum &b) {
mpz_init(value);
mpz_set(value, b.value);
}
~bignum() {
//clear value
}
bignum& operator = (const bignum &b) {
if (this != &b) mpz_set(value, b.value);
return (*this);
}
bignum operator + (const bignum &b) {
bignum res;
mpz_add(res.value, value, b.value);
return res;
}
bignum operator * (const bignum &b) {
bignum res;
mpz_mul(res.value, value, b.value);
return res;
}
};
int main()
{
bignum a = 5, b = 10, c = 15;
bignum res = 0;
check = true;
res = (a+b)*c + a;
cout << (*res.value) << "\n";
return 0;
}
我必须将高度优化的低级C代码包装到C ++类中。计算表达式res = (a+b)*c + a
时,将为tmp1
创建一个临时对象a+b
,为(a+b)*c
创建一个tmp2,为tmp3
创建一个(a+b)*c + a
,然后创建res = tmp3;
这似乎非常浪费,因为临时变量要消失需要3 mpz_init()。无论如何,我可以做些什么来降低成本吗?
谢谢。
您可以尝试使用单个静态bignum进行操作,并将运算符移到类外,如下所示: