dimanche 22 juillet 2018

C++: Stack vs Heap and templates

Let's assume we have the following template.

template <unsigned int size> class UnsignedInt {
public:
    UnsignedInt() : _hash() { }

    UnsignedInt<size> operator-(const UnsignedInt<size> &other) const {
        bool Bin = false;
        bool D1, D2, Bout1, Bout2;
        auto hash = new UnsignedInt<size>();

        for (int i = 0; i < size; ++i) {
            D1 = _hash[i] ^ other.At(i);
            Bout1 = other.At(i) & ~_hash[i];
            D2 = D1 ^ Bin;
            Bout2 = Bin & ~D1;

            Bin = Bout2 | Bout1;
            hash->SetAt(i, D2);
        }

        return *hash;
    }

private:
    std::bitset<size> _hash;
};

Which does not work, for reasons I'm trying to understand. The error which I'm getting with this solution is linking error that symbol for subtraction function is not found. Now I figured out that instead of using heap I can use the stack, I've tried it out and everything works great.

The following implements problem free full subtractor template:

template <unsigned int size> class UnsignedInt {
public:
    UnsignedInt() : _hash() { }

    UnsignedInt<size> operator-(const UnsignedInt<size> &other) const {
        bool Bin = false;
        bool D1, D2, Bout1, Bout2;
        UnsignedInt<size> hash;

        for (int i = 0; i < size; ++i) {
            D1 = _hash[i] ^ other.At(i);
            Bout1 = other.At(i) & ~_hash[i];
            D2 = D1 ^ Bin;
            Bout2 = Bin & ~D1;

            Bin = Bout2 | Bout1;
            hash.SetAt(i, D2);
        }

        return hash;
    }

private:
    std::bitset<size> _hash;
};

Can somebody explain to me why solution 1) has the linking problems while solution 2) works fine?

Thanks

Aucun commentaire:

Enregistrer un commentaire