C ++:null引用 [英] C++: null reference

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

问题描述

这段代码是否有效(以及定义的行为)?

Is this piece of code valid (and defined behavior)?

int &nullReference = *(int*)0;

g ++和clang ++编译时没有任何警告,即使使用 -Wall -Wextra -std = c ++ 98 -pedantic -Weffc ++ ...

Both g++ and clang++ compile it without any warning, even when using -Wall, -Wextra, -std=c++98, -pedantic, -Weffc++...

实际上是null,因为它不能被访问(它将意味着解引用一个空指针),但是我们可以通过检查它的地址来检查它是否为null:

Of course the reference is not actually null, since it cannot be accessed (it would mean dereferencing a null pointer), but we could check whether it's null or not by checking its address:

if( & nullReference == 0 ) // null reference


推荐答案

引用不是指针。

8.3.2 / 1:

8.3.2/1:


引用应初始化为
引用有效的对象或函数。
[注:特别是,一个空引用
不能存在于一个定义良好的
程序中,因为
创建这样一个引用的唯一方法是
绑定到通过
获得的对象,取消引用一个空指针,其中
引起未定义的行为。由于
在9.6中描述,引用不能
直接绑定到位字段。 ]

A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the "object" obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]

1.9 / 4:


某些其他操作在本国际标准中被描述为

undefined(例如,
取消引用空指针的效果)

Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer)

正如Johannes在一个被删除的答案中所说的,有一些人怀疑是否应该将解除引用一个空指针明确地声明为未定义的行为。但这不是一个引起怀疑的情况,因为空指针肯定不指向有效的对象或函数,并且标准委员会中没有引入空引用的愿望。

As Johannes says in a deleted answer, there's some doubt whether "dereferencing a null pointer" should be categorically stated to be undefined behavior. But this isn't one of the cases that raise doubts, since a null pointer certainly does not point to a "valid object or function", and there is no desire within the standards committee to introduce null references.

这篇关于C ++:null引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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