static_assert is all you need (no leaks, no UB)
twitter.com
twitter.com
However the standard only requires this for language-level undefined behavior. For undefined behavior happening in the standard library it's unspecified whether the expression is a constant expression or not. So no, constexpr tests don't cover all possible UB.
Also even if in theory language-level undefined behavior should be caught in constant expressions, in practice compilers miss a number of undefined behaviors. They are generally good at catching out-of-range indexing, using objects outside of their lifetime, using uninitialized values, signed integer overflow and modifying const objects. However there are a number of subtle undefined behaviors that they don't catch, like unsequenced operations on the same object, invalid values for unscoped enums.
There might be some overlap with runtime tests with -fsanitize=undefined,address. For catching uninitialized values at runtime though you probably need msan, which is a pain to set up, but constexpr tests cover that. On the other hand the function you test might not be available at compile-time.
Anyway, constexpr tests are a valuable tool. It's not a silver bullet.
Point 8:
> A core constant expression is any expression whose evaluation would not evaluate any one of the following:
> 8. an expression whose evaluation leads to any form of core language undefined behavior (including signed integer overflow, division by zero, pointer arithmetic outside array bounds, etc).
For example, here is a modification of the original program that does invoke UB, but compiles just fine:
<source>:5:17: error: static assertion expression is not an integral constant expression
static_assert(1024*1024*1024*3 != 0, "UB");
https://godbolt.org/z/Wc591En7E constexpr int foo(int x) {
return 1024*1024*1024*x;
}
int main()
{
int y;
std::cin >> y;
static_assert(foo(1)); //all good
foo(y); //oops, UB if user enters 7
}
https://godbolt.org/z/K8h4Kj99sEdit: small correction so that the numbers are big enough to cause problems...
I was pointing out that this is only true for the cases you actually test, not the general case.
Even then, it's not fully true, as a function may have different behavior at runtime as opposed to compile time (e.g. because of multi-threading), and so it may display UB even when called with the same arguments that didn't display UB at compile-time.
Overall, this static_assert trick is just a nice way to make sure your tests don't accidentally pass while still invoking UB, to protect from false negatives.
constexpr requires that the function be callable at compile-time, not that it is so.
The tweet seems to imply that if you can call your functions at compile time, they will not present UB at runtime either. I am trying to point out that that is not the case at all.
The input being potentially known at compile-time is not sufficient to make a constexpr function be called at compile-time.
Conversely, the origin of the thread implies that if a function has been successfully called with some argument from a static_assert, it will not have UB at runtime even if called with some other arguments. This subthread was showing that this is not the case, and that you can't test all uses of a function using static_assert to guarantee that it will not exhibit UB.
In case it's not clear, this piece of code will also fail to compile, even though it exhibits no UB:
constexpr int foo(int y) {
return y;
}
int y;
std::cin>>y;
static_assert(foo(y));
https://godbolt.org/z/xvhP8nq7zOf course, cannot be relied upon.
Otherwise, what you write is provably correct - UB is not statically decidable in all cases (and depending on the type of UB, not even in a lot of cases).
If your compile time evaluations don't trigger signed integer overflow (or any other UB) does it follow that at runtime you couldn't pass a parameter that would trigger signed overflow?
I mean it's still useful because at least you know your test code is not artificially passing because of some UB makes it look like passing
Right, that's the extent of what this does. When I saw it on r/cpp I thought OK, somebody realised now they can make their C++ tests work as a reasonable person would expect, or perhaps realised that without this C++ tests are almost worthless because they can invoke Undefined Behaviour silently.
But increasingly I suspect the OP mistook this for a breakthrough in correctness which it isn't, otherwise why post it to HN?
On the other hand, the prohibition on UB for constexpr doesn't reach up to where IFNDR lives, so I'd guess most non-trivial C++ software is technically nonsense with no defined meaning as a result of IFNDR regardless of how many or few unit tests were written or whether they use constexpr to prohibit Undefined Behaviour. A cheerful thought.
[Ill-Formed, No Diagnostic Required: A recurring statement in the C++ ISO document which basically says if you did this then too bad, that's not a well-formed C++ program, however your compiler may not notice that this isn't a C++ program, so, your program might compile, and even execute, but what if anything happens when you run it isn't specified in this ISO standard, good luck.]
That is, conditional constepxr code that depends on values and could produce UB is not valid constexpr code, and a compiler is not supposed to compile it.
This is very explicit in the standard.
Think of it as a statically decidable set of code.
Now, it wouldn't shock me if compilers don't achieve this right now, but the standard is clear that constexpr code may not contain operations that could produce undefined behavior at runtime.
A constexpr function can very well take an input, and it can invoke UB based on the runtime value of that input.
What the standard prohibits is compile-time evaluation of an expression which invokes UB. So, if you actually call your function at compile-time with a constexpr value that ends up invoking UB in the function (say, an integer overflow), THEN the standard mandates that the compiler throw an error rather than compiling some random value in.
For example:
constexpr void foo(int x) {
std::cout << 1024 * 1024 * 1024 * x;
}
int main() {
static_assert(foo(100)); // will fail because computing 1024 * 1024 * 100 is signed integer overflow, which is UB
foo(100); // invokes UB at runtime; in practice, will perhaps print some overflowed value
}
Edit: I should also add that you can very well invoke UB in a constexpr expression if it is standard library UB and not core language UB (e.g. if you try to pop() from an empty std::vector).No, it cannot. It is not constant if it does that. As such, it cannot be used in in any context that requires a constant expression. It explicitly says the operations in a constexpr may not produce undefined behavior.
That isn't "may not produce undefined behavior except if you pass the wrong values at runtime or don't evaluate it". It says: "An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (6.8.1), would evaluate one of the following expressions:
…
an operation that would have undefined behavior "
In your case, the evaluation would evaluate (at runtime) an operation that would have undefined behavior.
It is true that where you do not require a constant expression, it does not require it be constexpr at all, but the question is whether an expression that produces undefined behavior is constexpr is "no".
The standard even clarified this to say that foo is simply considered non-constant in your example (IE it's not constexpr ).
IE see defect report 695
"The consensus of the CWG was that an expression like 1/0 should simply be considered non-constant; any diagnostic would result from the use of the expression in a context requiring a constant expression. "
In your example, foo is non-constant as used. It is not constexpr.
Still, it should be noted that even code that looks identical to a core constant expression can display certain kinds of UB if invoked at runtime, per the standard. For example, if the code is using certain STL classes or threading constructs in a way that is UB, it can still be considered a core constant expression. Additionally, the code may be well defined when used in a single-threaded context, but become UB when used in multi-threaded contexts, say if two threads are accessing an object member concurrently without the right barriers.
Here is an example on godbolt. Notice that bar() and baz() are defined the same way in the static_assert block and the runtime block, yet executing them constitutes UB in one case but not the other.
But, this tells us nothing about whether calling the same function with some other argument would produce UB or not. Unless we try to form a core constant expression containing a call to that function for every possible argument value, we can't be sure if the function is free of UB for every possible input value.
My point, more simply, is: the fact that foo(1) is verified by the compiler to be a core constant expression is not a guarantee that foo(2) would be a core constant expression as well. Your original comment seems to me to imply that it does.
The consequence of this is that, as said elsewhere, this trick only helps to ensure that a unit test is not accidentally passing because of UB (and that memory is not leaked for that input value). It doesn't help provide any other guarantees.
If you use the same values at run time as you use in the tests, the tests predict the behavior as desired.
If you use different values at run time as you use in the tests, the tests do not predict the behavior as desired.
The GP post is explicitly claiming that the values don't matter, and that per the standard a constexpr function should be guaranteed by the compiler to be incapable of producing UB (or else compilation should fail and it should not be allowed to be declared constexpr). This is simply false. Here is the GP statement:
>> That is, conditional constepxr code that depends on values and could produce UB is not valid constexpr code, and a compiler is not supposed to compile it. [emphasis mine]
> If you use the same values at run time as you use in the tests, the tests predict the behavior as desired.
Even this is not fully guaranteed by the standard, as core constant expressions must only be guaranteed not to invoke core language UB. They may still be considered core constant expressions and evaluated at compile time even if they exhibit standard library UB (e.g. if they are not respecting some preconditions of an std::vector method).
They are so guaranteed - as i cited to you, your example of foo, as used in foo(100), is considered not a constant. There is no such thing as a constexpr expression that can produce UB.
If it can produce UB, it is not constexpr.
That does not mean it will not be validly usable in non-constant contexts! But it is not constexpr.
Not sure what you mean by a "constexpr expression" exactly. My point is that a function can legally be constexpr-qualified even if it can produce UB when called with certain arguments. I think it's very common to call such a function "a constexpr function". Of course, we agree that not every expression where a constexpr function is called is a constant expression (such as foo(100) in my example). However, expressions where that function is called with arguments where it does not produce UB are legal constant expressions (such as foo(1) in my example).
Perhaps I misunderstood your original comment and we are in fact in violent agreement. If so I apologize.
Source ?I am not sure constexpr give any garanty regarding UB and/or leaks
Can you point to a source for that ? I am not trying to be pendantic, but genuilly curious
I bet it's mostly a wash, and the ergonomics of conventional gtest macros look way better to my eye.
Basically the idea is that the test code gets written to a different linker section that your test runner can iterate through, when tests are enabled. This is easy on gcc because it generates automatic constants for the beginning and end of different linker sections. There may be away to do this with clang as well, but I never use clang.
You could of course set up your runtime tests in a similar way, having the ide run them back to back as you are writing code, but it is more complicated, especially if the code is in an intermediate state that it is not fully compilable.
So in the end it is not a huge breakthrough, but having compile time tests is still quite a nice feature.
[1]: https://en.cppreference.com/w/cpp/types/is_constant_evaluate...
The latter is pretty normal for other languages but is a big deal in C++ where UB is a constant plague. However many languages have either forbid or have strict limits on compile time heap allocation - after all that heap isn't going to still exist at runtime. Requiring that you free everything allocated fixes that hole and means you get free leak detection.
static_assert is a compile-time check.
[] { ... }(); is an immediately executed lambda function (IIFE in javascript parlance).
list<int> list{} is a linked list of integers (double-linked, forward and backward). push_back() allocates more memory. pop() / clean() deallocates memory.
I wonder what the compile time cost would be to just have this kind of unit testing in all the time.
Why is it a story? Slow day on the Internet?
In the end it just an excuse to have a discussion on an interesting topic.
And yes, it is a slow day.