Call member function of null pointer class without error

Time:2020-1-19

What is the reason for the null pointer instance to call the member function?

Guess what happens when the following example runs?

class A
{
public:
    static void print()
    {
        printf(">>>>>\n");
    }

    void print2()
    {
        printf("+++++\n");
    }

    void print3()
    {
        printf("====%d\n", value);
    }

private:
    int value;
};

int main(int argc, char *argv[])
{
    A *a = NULL;
    a->print();
    a->print2();
    a->print3();
    return 0;
}

Operation result:

A - > print() output: >
A - > print2() output:+++++
A - > print3() block error

The first two should bothSegment errorThat’s right. It’s working normally. In fact, all the above behaviors are caused bythisPointer left and right results.

0x00 static function does notthisPointer

   static methods are loaded as classes are loaded, and static methods do not need to be instantiated. It will not refer to the data in this pointer, sostatic void print()No error will be reported.

0x01 member function not usedthisPointer error free

  a->print();It can be approximately regarded asvoid print(A *a)Call, expand as follows:

void print(A *a)
{
    printf("+++++\n");
}

   an example of this aaThe pointer is not used and will not access to the wrong address and cause an exception.

0x02 null pointer refers to instance member for exception

  void print3()The value member of instance a is used in. Because a is empty and does not point to specific memory, there is an error referring to value memory.

0x03 summary

                 Null pointer instance references member variableResulting in.


More interesting articles, please pay attention to WeChat public number: “Qt Jun”.