c++ - C++ 标准的哪一部分涵盖通过空指针调用方法?

标签 c++ standards

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/

相关文章:

c++ - 如何在 C++ 中组合 `this` 和指针?

c++ - 检测文件 C++ 的最后一行

c++ - 什么是 ISO14882 和 ECMA335 标准的有效标识符?

c - printf float 的默认精度的历史是什么?

c++ - 即使使用 lpthread 也有 undefined reference to `pthread_join' 错误

c++ - 自定义迭代器运算符重载

c - 为什么十六进制 float 需要指定指数?

c++ - 关于long long和long double

c++ - 标准有误?

c++ - 不要用 "two-stage name lookup"得到它