通过取消引用NULL指针来分配引用 [英] Assigning a reference by dereferencing a NULL pointer

查看:611
本文介绍了通过取消引用NULL指针来分配引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int&  fun()
{
    int * temp = NULL;
    return *temp;
}



在上面的方法中,我试图做一个NULL指针的解引用。当我调用这个函数它不给出异常。我发现当返回类型是通过引用它不给出异常,如果它是通过值然后它。即使当NULL指针的解引用被赋值给引用(如下面的行)时,也不会给出。

In the above method, I am trying to do the dereferencing of a NULL pointer. When I call this function it does not give exception. I found when return type is by reference it does not give exception if it is by value then it does. Even when dereferencing of NULL pointer is assinged to reference (like the below line) then also it does not give.

int* temp = NULL:
int& temp1 = *temp;

这里我的问题是,编译器在引用的情况下不进行解引用吗?

Here my question is that does not compiler do the dereferencing in case of reference?

推荐答案

取消引用空指针未定义行为

未定义行为意味着任何事情都可能发生,因此无法定义行为。

An Undefined Behavior means anything can happen, So it is not possible to define a behavior for this.

不确定的是,我将第n次添加这个C ++标准报价,但似乎需要。

Admittedly, I am going to add this C++ standard quote for the nth time, but seems it needs to be.

关于未定义的行为,

C ++标准版1.3.24说明:

C++ Standard section 1.3.24 states:


允许未定义的行为范围该情况完全具有不可预测的结果,在以文件化的环境特征(有或没有诊断消息的发布)的方式执行翻译或程序期间行为,终止翻译或执行(发出诊断消息)。

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

注意

此外,请注意: br>
使用返回的引用或指向函数内的局部变量的指针也是未定义的行为。你应该使用new分配指针在freestore(堆),然后返回一个引用/指针。

NOTE:
Also, just to bring it to your notice:
Using a returned reference or pointer to a local variable inside a function is also an Undefined Behavior. You should be allocating the pointer on freestore(heap) using new and then returning a reference/pointer to it.

编辑:

正如@James McNellis在评论中恰当地指出,

如果未使用返回的指针或引用,则行为明确

这篇关于通过取消引用NULL指针来分配引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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