c++ - C/C++ nullptr 取消引用

标签 c++ c null nullptr

自从取消引用 nullptr ( NULL ) 是 C 中的未定义行为和C++ ,我想知道是否表达式 &(*ptr)如果 ptr 为 nullptr 则为有效。 (NULL)。

如果也是未定义的行为, OFFSETOF 怎么办?链接答案中的宏有效吗?

我一直以为ptr->field(*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.

关于c++ - C/C++ nullptr 取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38615436/

相关文章:

c++ - 密码破解代码优化;

c - 我应该如何理解这个迭代函数

使用 Xcode 控制到达非 void 函数 C 编程的末尾

c - printf() : When is %n written?

c++ - 如何判断未知类型数组的索引是否为空?

c++ - OpenCV、OpenFramework 和处理框架之间有什么区别?

c++ - 将值传递给功能模板的最佳方法

c++ - 如何修复 "ambiguous"函数调用?

null - 我们应该使用 Option 还是 ptr::null 来表示 Rust 中的空指针?

java - 如何验证复制构造函数的参数?