4 ms·
UB is not allowed in a constant expression in c++, which is a good reason to put constexpr in front of as many things as you can.
by hoosieree 4y ago
UB is not allowed in a constant expression in c++, which is a good reason to put constexpr in front of as many things as you can.
- gpderetta 4y agoYou need to actually invoke at compile time your constexpr function with the specific arguments that would cause UB to actually get an error. It is not significantly better than running your test cases with with UBsan but it is a nice feature.
- hoosieree 4y agoGood point. Also UBsan and Asan are great additions to any C/C++ workflow. But if it's actually part of the code, I'm forced to use it even if I'm lazy, versus an external tool that I can forget to run (or forget to add to my build system). Leveraging what the compiler gives you is like that saying "the best camera is the one you have on you".
- gpderetta 4y agoGood point. I love constexpr because it allows me to write compile time unit tests inline with the library code, with static_assert. The implied UB check is gravy.
- leni536 4y agoWhile theoretically true, there are a whole bunch of undefined behaviors that are not caught in constexpr context in practice. In particular unsequenced operations on the same object are typically not caught. It's still super useful though, and more common language UBs are caught.
- hoosieree 4y agoThat's a compiler bug though, right? Doesn't the standard disallow UB in constexpr?
- leni536 4y agoIt is. Or if it is unfeasible to implement then it can be considered to be a defect in the standard. Consider that something like (++*ptr1) + (++*ptr2) may or may not be UB, depending where the pointer points to. The required additional bookkeeping might make compile time evaluation unpractically slow. Alternatively the sequencing could be always defined between any two subexpressions within constexpr context.