为什么我可以使用无效的类指针进行函数调用

2021-12-13 00:00:00 function pointers c++

在下面的代码片段中,虽然指针没有初始化,但调用仍然成功

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

temp *ptr;
ptr->func2();

是C++语言属性的问题,还是VC++6编译器玩坏了?

Is it due to C++ language property, or it is VC++6 compiler which is foul playing?

class temp {
public:
    temp():a(9){}
    int& func1()
    {
        return a;
    }
    bool func2(int arg)
    {
        if(arg%2==0)
            return true;
        return false;
    }
    int a;
};

int main(int argc, char **argv)
{
    temp *ptr;
    int a;
    cin>>a;
    if(ptr->func2(a))
    {
        cout<<"Good poniner"<<endl;
    }
    ptr->func1(); // Does not crash here
    int crashere=ptr->func1();// But does crash here 
    return 0;
}

推荐答案

C++ 编译器不会阻止您使用未初始化的指针,虽然结果未定义,但现实世界中的编译器生成忽略的代码是正常的指针未初始化的事实.

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.

这是 C++ 相对于其他一些语言既快速又(相对)危险的原因之一.

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

您对 func2 的调用成功的原因是它没有触及它的 this 指针.指针值从未使用过,因此不会引起问题.在 func1 你do 使用 this 指针(访问成员变量),这就是它崩溃的原因.

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.

相关文章