C ++标准:取消引用NULL指针以获取引用? [英] C++ standard: dereferencing NULL pointer to get a reference?

查看:2282
本文介绍了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 / 4References)中调用了这种情况:

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.






一次我知道一个NULL指针可以以一个明确定义的方式解引用作为 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指针以获取引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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