search

Home  >  Q&A  >  body text

C++用空指针调用成员函数是未定义行为吗?

下面的代码:

class A {
public:
    void func(){}
    void func1(){a = 0;}
private:
    int a;
};

int main()
{
    A* a = 0;
    a->func();
    a->func1();
}

我使用vs2008和g++ 4.8.2编译,调用func()不会有问题,调用func1()会出错
但有人说调用func()也会出错(不知道是他确时出错,还是测试代码写的不一样导致出错)

所以我想知道空指针调用成员函数是未定义行为,由编译器决定如何做,还是C++标准有相关规定

高洛峰高洛峰2840 days ago732

reply all(5)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 11:29:04

    The this of a member function can be a null pointer, as long as this is not used explicitly/implicitly in the member function. This is because this in C++ is actually the last parameter of the function, nothing special, so there is no undefined behavior in it.

    This feature actually has no special use. I only use this feature a little in chain calls of certain pointers.

    For example:

    Foo *foo = ...;
    foo->bar()->play();
    

    bar and play are both functions that return Foo *, so if you write if (!this) return nullptr; inside, you can easily implement chain calls without checking the return value.

    reply
    0
  • 黄舟

    黄舟2017-04-17 11:29:04

    Of course it is Undefined behavior. Just when you thought it was not wrong, it has quietly contacted the Trisolarans and given them the coordinates of the sophons.
    Closer to home, the so-called UB means that no one can predict and be responsible for the consequences of this type of behavior. It may work normally under certain circumstances, but there is no guarantee.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 11:29:04

    I guess that as long as member variables, virtual functions and other things that require object addresses are not used, there should be no problem in calling that function. . . It's just that when the function is called, the register of this pointer is 0. .

    reply
    0
  • PHPz

    PHPz2017-04-17 11:29:04

    It also depends on the platform. Linux will definitely make mistakes. Unix usually has no problems, but there is no guarantee

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 11:29:04

    I will help you translate it into pure C code for you to take a look

    struct A{
        int a;
    };
    
    void fun(A* this)
    {
    }
    
    void func1(A* this)
    {
        this->a = 0;  // <--- 这里当然有问题啦
    }
    
    int main()
    {
        A* a = 0;
        fun(a);
        fun1(a);
    }
    

    Then understand it yourself. Virtual without using C++ is almost like this. If some of the people above don’t move, don’t answer.

    reply
    0
  • Cancelreply