C/C++ nullptr 取消引用

C/C++ nullptr dereference

由于取消引用 nullptr (NULL) 在 CC++ 中都是未定义的行为,我想知道表达式 &(*ptr) 是否是一个有效的 ptr 是 nullptr (NULL).

如果这也是未定义的行为,链接答案中的 OFFSETOF 宏如何工作?

我一直认为 ptr->field 是 shorthand for (*ptr).field

我认为我的问题的答案在 C 和 C++ 中是相似的。

TL;DR &(*(char*)0) 定义明确。

C++标准并没有说空指针本身的间接寻址有UB。当前标准草案,[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. If the type of the expression is “pointer to T”, the type of the result is “T”. [snip]

  2. The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. [snip]

除非间接表达式的左值转换为右值,否则没有 UB。


C 标准更加明确。 C11标准草案§6.5.3.2

  1. The unary & operator yields the address of its operand. If the operand has type "type", the result has type "pointer to type". If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue. Similarly, if the operand is the result of a [] operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result is as if the & operator were removed and the [] operator were changed to a + operator. Otherwise, the result is a pointer to the object or function designated by its operand.

If it is also an undefined behavior, how does offsetof work?

更喜欢使用 the standard offsetof macro。自行开发的版本会导致编译器警告。此外:

offsetof is required to work as specified above, even if unary operator& is overloaded for any of the types involved. This cannot be implemented in standard C++ and requires compiler support.

offsetofbuilt-in function in gcc.