Boost logo

Boost :

Subject: Re: [boost] Is there interest in portable integer overflow detection, with policy based handling?
From: Vicente J. Botet Escriba (vicente.botet_at_[hidden])
Date: 2012-02-24 08:25:59


Le 24/02/12 10:21, Ben Robinson a écrit :
> On Fri, Feb 24, 2012 at 12:31 AM, Vicente J. Botet Escriba<
> vicente.botet_at_[hidden]> wrote:
>
>
> But maybe, what verified_int is modeling is an integer type that doesn't
> converts to other verified_int types and checks for overflow. Is this what
> your library is designed for?
>
> Thank you for your thoughtful input. You are correct in that my
> verified_int class checks for overflow while preventing any implicit
> conversion of it's underlying representation. This has certain
> advantages. Consider a small code refactor which is not expected to change
> behavior (assume no compiler optimizations):
>
> // One math operation per line:
> verified_uint8_t a = 250;
> uint8_t b = 10;
> verified_uint8_t temp = a + b; // This will overflow
> verified_uint8_t c = temp - b; // We already overflowed above
Now that we have auto in C++11, I think that intermediates could be
stored using auto. So the preceding could be written as

verified_uint8_t a = 250;
uint8_t b = 10;
auto temp = a + b; // This should NOT overflow
verified_uint8_t c = temp - b; // c is equal to a

> //Now two operations on the same line:
> verified_uint8_t a = 250;
> uint8_t b = 10;
> verified_uint8_t c = a + b - b; // This will also overflow (as currently
> implemented)
>
> However, if the result of a+b can return common_type<A,B>::type which will
> then subtract b, and then be implicitly converted to verified_uint8_t, the
> overflow will be avoided.
Well, a+b should in addition use promotion to a larger type to avoid
overflow (when possible of course).
>
> But now that I think more about this, the language will cause an overflow
> on assignment in the first example, and the language will avoid the
> overflow in the second example due to the type of the temporary being
> chosen by the compiler.
Note that the use of a specific shorter temporary types is what is
requesting the overflow. The use of intermediary larger types (when
possible) avoids overflow.
When the user wants to check for overflow s/he just assigns the
expression to a variable with the wanted constraints.

Another possibility, and maybe what you are looking for, is to define
arithmetic operations with a specific result type, as e.g

template <typename Res, typename T, typename U>
Res add(T,U);

I don't know yet if what you look for is a closed and verified integer
type which is a different thing, with a quite different semantic respect
to the C++ integer built-in types.

closed_and_verified_int<T>
operator+(closed_and_verified_int<T>,closed_and_verified_int<T>);
> I will definitely put more thought into this. Excellent feedback.
>

Regards,
Vicente


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk