指针对象函数调用而不实例化它

Pointer obejct function call without instantiating it

我不明白以下调用 f() 的代码如何成功运行。由于对象 b 未使用 new 关键字实例化。 请帮助并提前感谢您的回答。

#include <iostream>
using namespace std;

class A{ public:
    void f(){cout<<"f";}
};

int main()
{
    A *b;
    delete b;
    b->f();

    return 0;
}

I don't understand how does following code called f() function successfully.

该程序具有 未定义的行为,因为 b 未初始化并且也未指向由 new 分配的内存。

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.

所以您看到(也许看到)的输出是未定义行为的结果。正如我所说,不要依赖具有 UB 的程序的输出。程序可能会崩溃。

所以使程序正确的第一步是删除 UB。 然后并且只有那时你可以开始对程序的输出进行推理。

例如,here the program doesn't crash but here它崩溃了。

要解决此问题,请确保指针 b 已初始化并指向由 new 分配的内存。


1有关未定义行为的更准确的技术定义,请参阅 this 其中提到:没有对程序行为的限制.