How is possible that accessing nullptr works? [duplicate]

做~自己de王妃 提交于 2019-12-02 10:24:16

Is that expected behavior?

No, it's UB, anything is possible.

Is it because getData() does not use "this"?

Yes, it might work because this won't be used in the special case, but nothing is guaranteed.

Basile Starynkevitch

It is undefined behavior, so you really should be very scared.

It might happen to apparently do something (on your implementation of C++), because the getData function is not virtual and don't use any member of B. So the generated code does not dereference the null pointer.

It is undefined behaviour, you are accessing a member method from a nullptr. No particular behaviour or outcome would be defined.

In this case though; given (cppreference):

The keyword this is a prvalue expression whose value is the address of the object, on which the member function is being called.

Since the NULL value of this is not being dereference - the member method is not virtual and doesn't access any member data of this - it "seems" to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!