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.
这篇关于在什么时候取消引用空指针会变成未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在什么时候取消引用空指针会变成未定义的行为
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
