Why am I able to make a function call using an invalid class pointer

后端 未结 6 615
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 01:56

In below code snippet, although pointer is not initialized the call is still made successfully

temp *ptr;
ptr->func2();

Is it due to C++

6条回答
  •  醉酒成梦
    2020-12-02 02:47

    This is entirely compiler-dependent and undefined behaviour according to the standard. You shouldn't rely on this.

    Call to func2() succeeds because the exact method to call is known at compile time (the call is not virtual) and the method itself doesn't dereference this pointer. So invalid this is okay.

    ptr->func1(); // This works
    

    because the compiler is instructed to return the reference to the class member. To do so it simply adds the offset of the member to the invalid value of this pointer and that produces yet another invalid pointer (reference, which is almost the same).

    int crashere=ptr->func1();// Crashes here
    

    because now the compiler is instructed to retrieve the value via that invalid reference and this crashed the program.

提交回复
热议问题