意外输出,而不是运行时错误 [英] Unexpected output instead of runtime error

查看:166
本文介绍了意外输出,而不是运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很明显,谁知道背景魔法,但我不明白如何下面的代码提供正确的输出。我预计运行时错误。请帮助。

  class a 
{
public:
void print $ b {
cout<<Hello\\\
<< endl;
int d = 100;
cout<< d<< endl;
}

int val;
};


int main()
{
a * ptr;

ptr-> print();

return SUCCESS;
}

OUTPUT如下:

 您好

100


解决方案

没有魔法 - 你的代码有未定义的行为。在您的代码中,您不访问 ptr ,它隐式地传递给 print()



在其他几种情况下可能会发生这种情况:




  • 访问 a 实例的字段。它需要读取 *(this + field_offset),这将导致运行时错误。


  • 虚拟方法。我已知的实现使用 vtable 来做到这一点,通常存储为对象空间中的第一个指针,因此指向 vtable 的指针将与此相同,因此: vtable = * this


  • 其他情况取决于编译器和平台


    It might be obvious for who knows the background magic, but I could not understand how below code is giving correct output. I expected a runtime error. Please help.

    class a
    {
      public:
        void print()
        {
            cout<<"Hello\n"<<endl;
            int d = 100;
            cout<<d<<endl;
        }
    
        int val;
    };
    
    
    int main()
    {
       a* ptr;
    
       ptr->print();
    
       return SUCCESS;
    }
    

    OUTPUT is as below :

    Hello
    
    100
    

    解决方案

    There is no magic - your code has undefined behavior. In your code you do not access ptr which is implicitly passed to print() as this pointer, that is why no error happen.

    It may happen in several other cases:

    • Accessing fields of a instance. It will require to read memory *(this + field_offset) which will cause runtime error.

    • Accessing virtual methods. Implementations known to me use vtable to do that, which is usually stored as first pointer in object space, so pointer to vtable would be same as this, so: vtable = *this

    • Other cases, depending on compiler and platform

    NOTE: type conversion is omitted from examples with this

    这篇关于意外输出,而不是运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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