Here’s a simple question: in C++11 what’s the best way to put debug checks in constexpr functions? Since assert is not constexpr, the obvious doesn’t work:
constexpr bool in_range(int val, int min, int max)
{
assert(min <= max); // OOPS, not constexpr
return min <= val && val <= max;
}
In C++14 this is OK, but in code that must be portable to C++11 it’s not. This is a known problem, and the recommended solution is to use a throw expression on failure. This totally non-obvious solution has the neat effect of causing a compile-time error when the arguments are known at compile-time:
constexpr bool in_range(int val, int min, int max)
{
return (min <= max)
? min <= val && val <= max
: throw std::logic_error("Assertion failed!");
}
constexpr bool res1 = in_range(4, 1, 5); // OK
constexpr bool res2 = in_range(4, 5, 1); // Compile error!
int min = 1, max = 5;
bool b = in_range( 4, max, min ); // Exception!
That’s fine except for one thing: it turns runtime assertions — which should be unrecoverable — into “recoverable” runtime exceptions. That’s really, really bad. Assertions are used to detect logic errors in your program. If one fires, it means your your program state is suspect. There is no way to safely recover from an invalid program state, so an exception is the wrong tool for the job.
Let’s look at a couple of solutions:
Fix #1: noexcept
One fix is pretty simple: add noexcept to the constexpr function:
constexpr
bool in_range(int val, int min, int max) noexcept
{
return (min <= max)
? min <= val && val <= max
: throw std::logic_error("Assertion failed!");
}
int min = 1, max = 5;
bool b = in_range( 4, max, min ); // Terminate!
Notice that in_range is declared noexcept — but it throws on error! What happens when a propagating exception hits a noexcept? It’s game over, man. The runtime calls std::terminate, which shuts the process down. That’s what an assert is supposed to do.
Fix #2: std::quick_exit
Here’s another simple fix: We could define a assert_failure exception type that shuts the process down in its constructor:
struct assert_failure
{
explicit assert_failure(const char *sz)
{
std::fprintf(stderr, "Assertion failure: %s\n", sz);
std::quick_exit(EXIT_FAILURE);
}
};
Now, we can use assert_failure in our constexpr functions to catch bugs as follows:
constexpr bool in_range(int val, int min, int max)
{
return (min <= max)
? min <= val && val <= max
: throw assert_failure("min > max!");
}
Notice how the assert_failure constructor reports the error and then calls std::quick_exit. quick_exit is a new function in C++11 that pretty much just shuts the process down without calling any destructors for locals or global objects. That’s almost certainly what you want. If your program state is borked, executing a pile of arbitrary code is a bad idea. It could do more harm than good. Any code that absolutely must execute on termination no matter what should be registered with std::at_quick_exit. You should limit that to things like saving user edits into a look-aside for attempted recovery later. (But don’t corrupt known-good data!)
Fix #3: assert
The trouble with Fix #2 is that it interferes with debuggers, which know about assert and what to do when one fires. The third fix is to just use assert, but to do it in a sneaky way. Once again, we define an assert_failure type, but this time pass to the constructor a function that does the assert for us:
struct assert_failure
{
template<typename Fun>
explicit assert_failure(Fun fun)
{
fun();
// For good measure:
std::quick_exit(EXIT_FAILURE);
}
};
constexpr bool in_range(int val, int min, int max)
{
return (min <= max)
? min <= val && val <= max
: throw assert_failure(
[]{assert(!"input not in range");}
);
}
Now on runtime failures, we get the assert we really wanted in the first place:
assertion "!"input not in range"" failed: file "main.cpp", line 41, function: auto in_range(int, int, int)::(anonymou s class)::operator()() const Aborted (core dumped)
Summary
If you want to add debug checks your C++11 constexpr functions, throw and noexcept are your friends. Alternately, you can define an assert_failure exception type that makes no bones about shutting your process down RIGHT NOW, either with std::quick_exit or with the trusty ol’ assert macro.
Leave a Reply