在什么时候取消引用空指针会成为未定义的行为? [英] At what point does dereferencing the null pointer become undefined behavior?

查看:685
本文介绍了在什么时候取消引用空指针会成为未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int * 

如果我实际上没有访问取消引用的对象 p = 0;
int& r = * p; // undefined?
int * q =& * p; // undefined?

一个更实用的示例:我可以取消引用空指针来区分重载吗?

  void foo(Bar&); 
void foo(Baz&);

foo(*(Bar *)0); // undefined?






好吧,参考示例肯定是未定义的行为到标准:


一个空引用不能存在于定义良好的程序中,因为创建这样一个引用的唯一方法是绑定到通过取消引用空指针导致未定义行为获取的对象。


,强调的部分是模糊的。

解决方案是否是 / div>

是的,它是未定义的行为,因为规范说lvalue指定一个对象或函数(在第3.10节),它说的 * - 操作符,结果[解除引用]是一个左值,引用表达式所指向的对象或函数(在第5.3.1节)。



没有描述当你解引用一个空指针时会发生什么。这只是未定义的行为。


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.

Unfortunately, the emphasized part is ambiguous. Is it the binding part that causes undefined behavior, or is the dereferencing part sufficient?

解决方案

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.

这篇关于在什么时候取消引用空指针会成为未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆