Integer overflow

C++ Add comments

Recently, I read the article Integer Handling with the C++ SafeInt Class on MSDN which describes a generic C++ class that modifies the common mathematical operations (multiplication, addition, etc.) to throw an exception upon overflow. The method the author chose was to bounds check the operations before execution, which results in some tricky and non-obvious code.

Personally, I would have implemented the code in terms of inline x86 assembler. The code would become much, much simpler and probably quite a bit faster. The major downsides would be portability and writing all the partial template specializations.

I’m a little rusty on x86 assembly and a lot rusty on inline assembly, but the code might look something like:

template<>
SafeInt<int> operator +(int lhs, SafeInt<int> rhs)
{
    int ret;

    __asm {
        mov eax, lhs;
        mov ebx, rhs.Value();
        add eax, ebx;
        jo overflow;
        mov ret, eax;
    }

    return SafeInt<int>(ret);

overflow:
    throw OverflowException();
}

The savings are probably especially dramatic for the multiplication operator.

Comments are closed.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in