为什么用nullPtr调用函数不会使我的应用程序崩溃? [英] Why calling function with nullPtr does not crash my application?
问题描述
我不了解C ++的知识-我在类上创建了一些指针并将其设置为null.
I don't understand something in C++ - I create some pointer on class and set it to null.
现在,我使用此空指针调用某些函数,该函数成功.为什么不崩溃?
Now I call some function with this null pointer and the function succeeds. Why doesn't it crash ?
class Entity
{
public:
void Print() const
{
std::cout << "Print" << std::endl;
}
};
int main()
{
Entity* ptr = nullptr;
Entity& _ref = *ptr; // No crash here - I expected a null pointer exception
_ref->Print();
}
推荐答案
这在C ++中很常见,该函数不是实例的一部分,而是类定义的一部分.
This is a common thing in C++, the function is not part of the instance, but part of the class definition.
如果您尝试访问该函数中的 this
,则将导致崩溃.
If you tried to access this
in the function then you would have a crash.
如下面提到的@YSC一样,这被认为是未定义的行为,您不应认为这会起作用.但是它通常可以正常工作,而且我听说这在C ++访谈中甚至被问到了问题.
As @YSC mentioned below, this is considered undefined behavior, and you should not assume this will work. but it will mostly work and i heard this is even asked in C++ interviews questions.
这篇关于为什么用nullPtr调用函数不会使我的应用程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!