通过取消引用 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 节规定:

允许的未定义行为范围从完全忽略情况并产生不可预测的结果,在翻译或程序执行期间以环境特征的文档化方式(有或没有发布诊断消息),到终止翻译或执行(随着诊断消息的发布).

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).

注意:
另外,只是为了引起您的注意:
使用返回的引用或指向函数内局部变量的指针也是未定义行为.您应该使用 new 在 freestore(heap) 上分配指针,然后返回指向它的引用/指针.

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,在评论中适当指出,
如果未使用返回的指针或引用,则行为定义良好.

相关文章