C/C ++ nullptr取消引用 [英] C/C++ nullptr dereference

查看:228
本文介绍了C/C ++ nullptr取消引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为在CC++中都取消引用nullptr(NULL)是未定义的行为,所以我想知道如果ptr为nullptr().

Since de-referencing nullptr (NULL) is an undefined behavior both in C and C++, I am wondering if expression &(*ptr) is a valid one if ptr is nullptr (NULL).

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

If it is also an undefined behavior, how does OFFSETOF macro in the linked answer work?

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

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

I think the answer to my question is similar in C and C++.

推荐答案

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

TL;DR &(*(char*)0) is well defined.

C ++标准没有说空指针本身具有UB.当前标准草案 [expr.unary.op]

The C++ standard doesn't say that indirection of null pointer by itself has UB. Current standard draft, [expr.unary.op]

  1. 一元*运算符执行间接操作:应用该表达式的表达式应是指向对象类型的指针或指向函数类型的指针,并且结果是指向对象或函数的左值表达点.如果表达式的类型为"T的指针",则结果的类型为"T". [snip]

  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]

一元&的结果运算符是指向其操作数的指针.操作数应为左值或限定ID. [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.

There is no UB unless the lvalue of the indirection expression is converted to an rvalue.

C标准更为明确. C11标准草案§6.5.3.2

The C standard is much more explicit. C11 standard draft §6.5.3.2

  1. 一元&运算符产生其操作数的地址.如果操作数具有类型"type",则结果具有类型"pointer to type". 如果操作数是一元*运算符的结果,则该运算符和&对运算符进行求值,结果好像都被省略了,除了运算符上的约束仍然适用并且结果不是左值.同样,如果操作数是[]运算符的结果,则&运算符或[]所隐含的一元*都会被求值,结果就像 &删除了运算符,并将[]运算符更改为+运算符.否则,结果是指向由其操作数指定的对象或函数的指针.
  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 ++ nullptr取消引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆