为什么当我通过C ++中的空指针调用成员函数时程序崩溃? [英] Why doesn't the program crash when I call a member function through a null pointer in C++?

查看:534
本文介绍了为什么当我通过C ++中的空指针调用成员函数时程序崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "iostream"
using namespace std;
class A
{
public:
    void mprint()
    {
        cout<<"\n TESTING NULL POINTER";
    }
};

int main()
{
    A *a = NULL;
    a->mprint();
    return 0;
}

我输出为TESTING NULL POINTER。任何人都可以解释为什么这个程序是打印输出,而不是崩溃。我检查它在Dev C ++和aCC编译器都给出相同的结果。

I am getting output as "TESTING NULL POINTER". Can anyone please explain why this program is printing the output instead of crashing. I checked it on Dev C++ and aCC compiler both gave same result.

推荐答案

你不使用任何成员变量< c $ c> A - 该函数完全独立于 A 实例,因此生成的代码不包含任何取消引用0的内容。这仍然是未定义的行为 - 它可能会在一些编译器上工作。未定义的行为意味着任何事情都可能发生 - 包括程序恰好按照程序员的期望工作。

You're not using any member variables of A - the function is completely independent of the A instance, and therefore the generated code happens to not contain anything that dereferences 0. This is still undefined behavior - it just may happen to work on some compilers. Undefined behavior means "anything can happen" - including that the program happens to work as the programmer expected.

make mprint virtual你可能会得到一个崩溃 - 或者如果编译器发现它不需要一个vtable,你可能得不到一个。

If you e.g. make mprint virtual you may get a crash - or you may not get one if the compiler sees that it doesn't really need a vtable.

如果您向A添加一个成员变量并打印,将会导致崩溃。

If you add a member variable to A and print this, you will get a crash.

这篇关于为什么当我通过C ++中的空指针调用成员函数时程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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