为什么我能够使用无效的类指针进行函数调用 [英] Why am I able to make a function call using an invalid class pointer

查看:114
本文介绍了为什么我能够使用无效的类指针进行函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码片段中,尽管指针未初始化,调用仍然成功。

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;
}


推荐答案

防止你使用未初始化的指针,虽然结果是未定义的,但在现实世界中编译器生成的代码忽略了指针未初始化的事实是正常的。

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.

调用 func2

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.

这篇关于为什么我能够使用无效的类指针进行函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆