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

后端 未结 6 600
没有蜡笔的小新
没有蜡笔的小新 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:35

    You can call the methods using uninitialised pointers. It will work either ptr->func1(); or int crashere=ptr->func1();//

    0 讨论(0)
  • 2020-12-02 02:36

    The C++ compiler doesn't prevent you from using uninitialised pointers, and although the results are undefined, it's normal for compilers in the real world to generate code that ignores the fact that the pointer is uninitialised.

    It's one of the reasons why C++ is both fast and (comparatively) dangerous relative to some other languages.

    The reason your call to func2 succeeds is that it doesn't touch its this pointer. The pointer value is never used, so it can't cause a problem. In func1 you do use the this pointer (to access a member variable), which is why that one crashes.

    0 讨论(0)
  • 2020-12-02 02:36

    Its not working. Its just by luck that your application is not crashing where your expecting it to crash. Its not a feature but a side-effect of the compiler which is allowing the function call to seem to work.

    0 讨论(0)
  • 2020-12-02 02:41

    I suspect that ptr->func2() is optimised away as it always returns true. But as Richie says, the use of the pointer is fine in this case as you;re not touching any instance data (a) and as such there is nothing to crash into.

    0 讨论(0)
  • 2020-12-02 02:44

    C++ has the notion of Undefined Behavior. Using an uninitialized pointer is a common example of such Undefined Behavior. For performance reasons, the C++ standard places no restrictions whatsoever on the possible outcome. That is to say, formatting the harddisk is perfectly acceptable.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题