Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

the one about unsigned integers with one bit missing would be trivial to implement as a library in C++ with no significant downside. all you have to do is make a class wrapping a signed int and put debug checks for if the high 1 bit is set behind an if constexpr in operator= and the copy constructor. in most other languages this would bring a big performance penalty, but this is one thing that C++ is actually very good at.


This is incorrect. For one thing, you're going to need to overload all the operators that mutate the integer in place, e.g. operator++, operator +=, operator -=, operator *=, shifts, etc. And those checks can be quite expensive. For example, your code is probably littered with for loops that are implemented using operator++ or operator+=, and that means on every loop iteration you need to check for overflow, which is expensive if the loop body is simple. GCC and Clang already implement -ftrapv which does something similar (it adds compiler checks at all places where signed integers can overflow and trap if overflow occurs). I've used -ftrapv in debug builds but for most programs you don't want it in non-debug builds because the overhead is too high.


the "if constexpr" makes sure the checks only happen in debug mode. you'd definitely want to turn the checks off for release builds.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: