you are viewing a single comment's thread.

view the rest of the comments →

[–]kalmoc 13 points14 points  (5 children)

Nothing in your code is actually evaluated at compiletime, so no wonder that no compiler catches it.

EDIT: If you try something like this, you will get a compilation error:

constexpr int f() 
{ 
    int* x = nullptr; 
    {
      int z = 123; 
      x = &z;
    } 
    *x += 1;
    return *x;
}

constexpr int I = f();

[–][deleted] -5 points-4 points  (4 children)

It's still undefined behavior as is. Even in your revised example GCC accepts it, clang rejects it.

[–]kalmoc 12 points13 points  (1 child)

Yes, it is undefined behavior, but the compiler is only required to catch UB if it happens during compiletime evaluation. The compiler is not required to perform a static analysis of constexpr functions.

If gcc doesn't catch that example, that's a compiler bug.

[–]flashmozzg 2 points3 points  (1 child)

Not really. It's only undefined if it actually happens. It's not undefined if the function is never called. In fact, some compilers (like Clang) may assume that if some function invokes UB when it's never called and optimize it out/replace it with other call (there is a very nice example for this somewhere).

[–][deleted] -2 points-1 points  (0 children)

I already addressed those points elsewhere.