At what point does dereferencing the null pointer become undefined behavior?(在什么时候取消引用空指针会变成未定义的行为?)
问题描述
如果我没有真正访问解引用的对象",解引用空指针是否仍然未定义?
If I don't actually access the dereferenced "object", is dereferencing the null pointer still undefined?
int* p = 0;
int& r = *p; // undefined?
int* q = &*p; // undefined?
一个稍微实际一点的例子:我可以取消引用空指针来区分重载吗?
A slightly more practical example: can I dereference the null pointer to distinguish between overloads?
void foo(Bar&);
void foo(Baz&);
foo(*(Bar*)0); // undefined?
<小时>
好的,根据标准,参考示例肯定是未定义的行为:
Okay, the reference examples are definitely undefined behavior according to the standard:
在定义良好的程序中不能存在空引用,因为创建这种引用的唯一方法是将它绑定到通过取消引用空指针获得的对象",这会导致未定义的行为强>.
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.
不幸的是,强调的部分是模棱两可的.是 binding 部分导致了未定义的行为,还是 取消引用 部分就足够了?
Unfortunately, the emphasized part is ambiguous. Is it the binding part that causes undefined behavior, or is the dereferencing part sufficient?
推荐答案
是的,它是未定义的行为,因为规范说左值指定一个对象或函数"(在第 3.10 条)并且它说 *
-操作符[解引用]的结果是一个左值,引用表达式指向的对象或函数"(见第 5.3.1 节).
Yes it is undefined behavior, because the spec says that an "lvalue designates an object or function" (at clause 3.10) and it says for the *
-operator "the result [of dereferencing] is an lvalue referring to the object or function to which the expression points" (at clause 5.3.1).
这意味着没有描述取消引用空指针时会发生什么.这只是未定义的行为.
That means there is no description for what happens when you dereference a null pointer. It's simply undefined behavior.
这篇关于在什么时候取消引用空指针会变成未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在什么时候取消引用空指针会变成未定义的行为


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01