Undefined behavior causing time travel

后端 未结 3 503
说谎
说谎 2020-11-30 13:08

One example of this article from a msdn blog made me ticker:

It says that this function:

void unwitting(bool door_is_open)
{
    if (door_is_open) {
         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 13:39

    It's true that undefined behaviour may happen only at runtime (e.g. dereferencing a pointer which happens to be null). Other times, a program may statically be "ill-formed, no diagnostic required" (e.g. if you add an explicit specialization for a template after it has already been used), which has the same effect, though: You cannot argue from within the language how your program will behave.

    Compilers can use UB to "optimize" code generation aggressively. In your case, the compiler sees that the second branch will cause UB (I assume that this is known statically, even though you didn't spell it out), and so it can assume further that that branch is never taken, since that's indistinguishable: If you did enter the second branch, then the behaviour would be undefined, and that includes behaving like you entered the first branch. So the compiler can simply consider the entire code path that leads to UB as dead and remove it.

    There's no way for you to prove that something is wrong.

提交回复
热议问题