为什么在C++中通过空指针调用成员函数时程序不会崩溃?

2023-12-02C/C++开发问题
2

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

问题描述

#include "iostream"
using namespace std;
class A
{
public:
    void mprint()
    {
        cout<<"
 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.

推荐答案

您没有使用 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.

如果你例如使 mprint 成为虚拟的,您可能会崩溃 - 或者如果编译器发现它并不真正需要 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++中通过空指针调用成员函数时程序不会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6