zoukankan      html  css  js  c++  java
  • 通过一个非法的指针或者NULL指针调用成员函数会发生什么?

    通过一个非法的指针或者NULL指针调用成员函数会发生什么?

    #include
     
    <iostream>
    

    struct foo
    {
       
    void bar () { std :: cout << "gman was here" << std :: endl ; }
       
    void baz () { x = 5 ; }

       
    int x ;
    };

    int main ()
    {
        foo
    * f = 0 ;

        f
    -> bar (); // (a)
        f
    -> baz (); // (b)
    }
    我们预计b会崩溃,因为对于NULL POINTER(空指针)没有相应的成员数据x。
    而在实践中,(a)不会crash,因为没有用到this指针。
    (b)会提领this指针,((*this).x=5;),但是this为NULL,所以程序行为未定义。
    那么(a)是否也是未定义了?



    对于E1->E2而言,这个表达式会变成(*(E1)).E2,那么此时也会对NULL POINTER进行提领,所以(a)的行为
    也是未定义的。
    但如果E2是一个static函数,那么*(E1)会被忽略,所以不会表现出UB。
  • 相关阅读:
    Codeforces Round #388(div 2)
    Codeforces Round #387(div 2)
    Codeforces Round #386(div 2)
    Codeforces Round #385(div 2)
    Codeforces Round #384(div 2)
    Wannafly Union Goodbye 2016
    写在2016的最后一天——给未来的自己
    2016HDU校赛
    2016BUAA校赛决赛
    codevs 1344 模拟退火
  • 原文地址:https://www.cnblogs.com/IS2120/p/6746057.html
Copyright © 2011-2022 走看看