C++ standard: dereferencing NULL pointer to get a reference?(C++ 标准:取消引用 NULL 指针以获取引用?)
问题描述
我想知道 C++ 标准对这样的代码是怎么说的:
I'm wondering about what the C++ standard says about code like this:
int* ptr = NULL;
int& ref = *ptr;
int* ptr2 = &ref;
在实践中,结果是 ptr2 为 NULL,但我想知道,这只是一个实现细节还是在标准中定义得很好?
在不同的情况下,取消引用 NULL 指针应该会导致崩溃,但在这里我取消引用它以获取由编译器作为指针实现的引用,因此实际上没有实际取消引用 NULL.
In practice the result is that ptr2 is NULL but I'm wondering, is this just an implementation detail or is this well defined in the standard?
Under different circumstances a dereferencing of a NULL pointer should result in a crash but here I'm dereferencing it to get a reference which is implemented by the compiler as a pointer so there's really no actual dereferencing of NULL.
推荐答案
取消引用 NULL 指针是未定义的行为.
Dereferencing a NULL pointer is undefined behavior.
事实上,标准在注释(8.3.2/4参考")中明确指出了这种情况:
In fact the standard calls this exact situation out in a note (8.3.2/4 "References"):
注意:特别是,在定义良好的程序中不能存在空引用,因为唯一的创建这样一个引用的方法是将它绑定到通过取消引用空指针获得的对象",这会导致未定义的行为.
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.
<小时>
顺便说一句:有一次我意识到可以以明确定义的方式取消引用"空指针是作为 sizeof 运算符的操作数,因为操作数sizeof 实际上并没有被评估(所以解引用从来没有真正发生过).
As an aside: The one time I'm aware of that a NULL pointer can be "dereferenced" in a well-defined way is as the operand to the sizeof operator, because the operand to sizeof isn't actually evaluated (so the dereference never actually occurs).
这篇关于C++ 标准:取消引用 NULL 指针以获取引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 标准:取消引用 NULL 指针以获取引用?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
