导致时间旅行的未定义行为 [英] Undefined behavior causing time travel

查看:295
本文介绍了导致时间旅行的未定义行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自msdn博客的这篇文章的一个例子使我ticker:



它说这个函数:

  void unwitting bool door_is_open)
{
if(door_is_open){
walk_on_in();
} else {
ring_bell();

//使用后备值等待门打开
fallback = value_or_fallback(nullptr);
wait_for_door_to_open(fallback);
}
}

可以优化到这一个:

  void unwitting(bool door_is_open)
{
walk_on_in
}

因为调用 value_or_fallback(nullptr)是未定义的行为(这在本文前面已经证明)。



现在我不明白的是:运行时进入未定义的行为,到达那条线。在第一段的所有可观察到的效果在运行时间进入UB之前已经解决的意义上,不应该发生在之前/发生之后的概念?

解决方案

在推理中有一个流程。



当编译器编写器说: ,有两种不同的解释:




  • 大多数人听到:我们识别未定义的行为,


  • ul>

    因此,在您的情况下:




    • 解除引用 nullptr
    • 因此执行 value_or_fallback(nullptr)是未定义行为

    • 因此执行 else 分支是未定义的行为

    • 因此 door_is_open false 是未定义的行为



    程序员发现她将遵循使用条款), door_is_open 必须 true ,编译器可以清除 else 分支。



    (*)我很轻slightly,Raymond Chen实际上是以这种方式制定的...


    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) {
      walk_on_in();
     } else {
      ring_bell();
    
      // wait for the door to open using the fallback value
      fallback = value_or_fallback(nullptr);
      wait_for_door_to_open(fallback);
     }
    }
    

    Can be optimized into this one:

    void unwitting(bool door_is_open)
    {
        walk_on_in();
    }
    

    Because calling value_or_fallback(nullptr) is undefined behavior (this is proven earlier in the article).

    Now what I don’t understand is this: the run time enters undefined behavior only when it reaches that line. Shouldn’t the happen-before / happen-after concept applies here, in the sense that all observable effects of the first paragraph have be resolved before the run time enters UB?

    解决方案

    There is a flow in the reasoning.

    When a compiler writer says: we use Undefined Behavior to optimize a program, there are two different interpretations:

    • most people hear: we identify Undefined Behavior and decide we can do whatever we want (*)
    • the compiler writer meant: we assume Undefined Behavior does not occur

    Thus, in your case:

    • dereferencing a nullptr is Undefined Behavior
    • thus executing value_or_fallback(nullptr) is Undefined Behavior
    • thus executing the else branch is Undefined Behavior
    • thus door_is_open being false is Undefined Behavior

    And since Undefined Behavior does not occur (the programmer swears she will follow the terms of use), door_is_open is necessarily true and the compiler can elide the else branch.

    (*) I am slightly annoyed that Raymond Chen actually formulated it this way...

    这篇关于导致时间旅行的未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆