Which part of the C++ standard covers calling a method via a null pointer?

≡放荡痞女 提交于 2019-12-24 05:27:12

问题


There are many questions on Stack Overflow that explain that the following is undefined behavior in C++:

MyType* p = nullptr;
p->DoSomething();

but I can't find one that cites the C++ standard. Which part of the C++11 and/or C++14 standards say that this is undefined behavior?


回答1:


C++14 [expr.ref]/2:

The expression E1->E2 is converted to the equivalent form (*(E1)).E2

C++14 [expr.unary.op]/1:

The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points.

The pointer does not point to an object, therefore this quote does not define the behaviour of *p. Nowhere else in the standard defines it either, so it is undefined behaviour.

Regarding whether a null pointer can be said to point to an object, N4618 [basic.compound]/3 defines pointer values as:

Every value of pointer type is one of the following:

  • a pointer to an object or function (the pointer is said to point to the object or function), or
  • a pointer past the end of an object, or
  • the null pointer value for that type, or
  • an invalid pointer value.

which indicates that the null pointer value does not point to an object.



来源:https://stackoverflow.com/questions/42570752/which-part-of-the-c-standard-covers-calling-a-method-via-a-null-pointer

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