Call member function of null pointer class without error


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

Guess what happens when the following example runs?

class A
    static void print()

    void print2()

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

    int value;

int main(int argc, char *argv[])
    A *a = NULL;
    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)

   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”.