C++ Call a non-virtual non-static method from a null pointer, without accessing members : is this guaranteed to work? [duplicate]

匆匆过客 提交于 2019-12-24 11:55:42

问题


Can I call a non-static, non-virtual method of a class from a null pointer? The member function would then test if this==nullptr, and return immediately if it's true.

I know it will work in most cases, but is this a guaranteed result? That way, I can ensure null pointer exceptions never happen, and avoid testing for null pointers in many places of the caller code. That's for compactness, I'm not going to do that right now, but I'm curious to know if any standard will guarantee this to work...

Thanks!


回答1:


Dereferencing a nullptr is Undefined behavior. Period!
Whether it works or not on one particular implementation is irrelevant, the behavior is not guaranteed.




回答2:


The standard expliticly mentions dereferencing NULL pointer as undefined behavior. Using opearator -> dereferences the pointer to left.

So you're okay only in case if your implementation defined some behavior for the case, as it is a possibility (though I never encountered it in real life yet).

(I hope you understand that observing something is not the same as being defined.)




回答3:


always avoid calling a null pointer, you would usually end up with a core dump




回答4:


There are interesting answers here: When does invoking a member function on a null instance result in undefined behavior?

Also, the standard gives no hint about the mechanism for calling member virtual functions. It is usually done by just passing 'this' as a hidden function argument, which will in practice not dereference the pointer and work. However, it seems possible to implement even non-virtual function with a vtable, which in this case would crash.

Interestingly, a Microsoft function relies on this behavior :) http://msdn.microsoft.com/en-us/library/d64ehwhz%28v=vs.80%29.aspx



来源:https://stackoverflow.com/questions/17238284/c-call-a-non-virtual-non-static-method-from-a-null-pointer-without-accessing

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