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?
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.