0
#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一个临时对象for 、 tmp2 for 、for ,然后tmp1a+b(a+b)*ctmp3(a+b)*c + ares = tmp3;

这似乎非常浪费,因为临时变量需要 3 mpz_init() 才会消失。无论如何我可以做些什么来降低这个成本?

谢谢你。

4

0 回答 0