自从取消引用 nullptr
( NULL
) 是 C
中的未定义行为和C++
,我想知道是否表达式 &(*ptr)
如果 ptr 为 nullptr
则为有效。 (NULL
)。
如果也是未定义的行为, OFFSETOF 怎么办?链接答案中的宏有效吗?
我一直以为ptr->field
是 (*ptr).field
的简写
我认为我的问题的答案在 C 和 C++ 中是相似的。
最佳答案
TL;DR &(*(char*)0)
定义良好。
C++ 标准并没有规定空指针本身的间接寻址具有 UB。当前标准草案,[expr.unary.op]
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]
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
- 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.
关于c++ - C/C++ nullptr 取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38615436/