为什么不崩溃? [英] Why doesn't this crash?

查看:66
本文介绍了为什么不崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我今天一直盯着屏幕太久了,因为我不确定我是否正确看到了这一点。以下是我正在查看的代码:



  #include  < span class =code-preprocessor> <   iostream   >  
使用 命名空间标准;

class SomeClass
{
public
void f();
};

void SomeClass :: f()
{
cout<< << endl;
}


int main()
{
SomeClass * sc;
sc = NULL;
sc-> f();

return 0 ;
}









这是输出:





在某个班级







为什么我得到这个输出?

解决方案

为了理解它,你应该理解实例的功能叫做。你的函数 f 的参数为零,但仍隐式传递一个隐藏参数: this ,指向班级的实例;在这种情况下,这是 sc

这个 this 用于访问该类的其他实例成员。



在您的情况下, sc 恰好为null。所以呢?它生成将null作为参数传递的代码。但它没有被使用!在功能上,您的功能类似于静态功能,它不需要呼叫实例。在您的情况下,生成的代码调用类方法并传递null,这不会改变任何内容。通话成功。



换句话说,你从来没有真正解除引用 sc ,因为它不需要生成一个函数调用,并且该方法的主体不会尝试取消引用null。当然,这是一种类型或C ++的怪异,但可以解释。



当然,你不必在实践中做类似的事情。实际上,这样的方法应该声明为 static



-SA

Maybe I have been staring at the screen too long today, because I'm not sure if I am seeing this correctly. Here is the code I am looking at:

#include <iostream>
using namespace std;

class SomeClass
{
    public:
    void f();
};

void SomeClass::f()
{
    cout<<"in some class"<<endl;
}


int main()
{
    SomeClass* sc;
    sc = NULL;
    sc->f();

    return 0;
}





And here is the output:


in some class




why am I getting this output?

解决方案

To understand it, you should understand how instance functions are called. Your function f has zero parameters, but one hidden parameter is still passed implicitly: "this", a pointer to the instance of the class; in this case, this is sc.
This "this" is used to access other instance members of the class.

In your case, sc happened to be null. So what? It generates the code which passed null as a parameter. But it is not used! Functionally, your function is similar to the static function, which does not need an instance for a call. In your case, the generated code calls the class method and passes null, which changes nothing. The call is successful.

In other words, you never really dereference sc, as it is not needed to generate a function call, and the body of the method does not do anything which would try to dereference null. Of course, this is a kind or C++ weirdness, but quite explainable.

You don't have to do something similar in practice, of course. In practice, a method like this should be declared static.

—SA


这篇关于为什么不崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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