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

Why am I able to make a function call using an invalid class pointer(为什么我可以使用无效的类指针进行函数调用)
本文介绍了为什么我可以使用无效的类指针进行函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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 指针.指针值从未使用过,因此不会引起问题.在 func1do 使用 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)