Is null reference possible?(可以空引用吗?)
问题描述
这段代码是否有效(和定义的行为)?
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++...
当然引用实际上不是空的,因为它不能被访问(这意味着取消引用一个空指针),但我们可以通过检查它的地址来检查它是否为空:
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:
一个引用应该被初始化为引用有效的对象或函数.[注意:特别是空引用不能存在于一个明确定义的程序,因为只有这样创建这样的引用将是将其绑定到通过获得的对象"取消引用一个空指针,它导致未定义的行为.作为在 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:
描述了某些其他操作在本国际标准中作为未定义(例如,效果取消引用空指针)
Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer)
正如约翰内斯在一个已删除的答案中所说的那样,是否应该将取消引用空指针"明确地声明为未定义的行为存在一些疑问.但这并不是引起怀疑的情况之一,因为空指针肯定不会指向有效的对象或函数",并且标准委员会内不希望引入空引用.
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.
这篇关于可以空引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可以空引用吗?
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
