Stack Overflow 上有很多问题解释了以下是 C++ 中未定义的行为:
MyType* p = nullptr;
p->DoSomething();
但我找不到引用 C++ 标准的内容。 C++11 和/或 C++14 标准的哪一部分规定这是未定义的行为?
最佳答案
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.
指针不指向对象,因此这句话没有定义*p
的行为。标准中的其他地方也没有定义它,因此它是未定义的行为。
关于空指针是否可以说指向一个对象,N4618 [basic.compound]/3将指针值定义为:
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.
这表明空指针值不指向对象。
关于c++ - C++ 标准的哪一部分涵盖通过空指针调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42570752/