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.
这篇关于在什么时候取消引用空指针会变成未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在什么时候取消引用空指针会变成未定义的行为
基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
