指向空对象的引用 [英] Reference pointing to a Null-object

查看:66
本文介绍了指向空对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这个讨论-在C ++中检查空对象令我惊讶的是,没有人谈论引用何时可以指向空对象.在我们的代码中,我们通常使用空对象.有如下返回nullObj的函数.

I saw this discussion - Checking for a null object in C++ and I was surprised that no one talked about when reference can point to a null object. In our code, we use null objects routinely. There are functions as follows which return nullObj.

const Obj&  
nullObj()  
{  
   static obj* nullPtr = NULL;   
   return static_cast<  const Obj&>(*nullPtr);    
}  

实际上,当我再次查看该代码以提出该主题时,我对上述代码的工作方式有一些疑问:

Actually, when I looked at the code again to bring this topic up, I had some questions on how the above code works:

  1. 怎么可能做*nullPtr-是因为nullPtr是一个静态对象,该对象在堆上分配了内存,因此可以保证有一定的空间和

  1. How is it possible to do *nullPtr - Is is it because nullPtr is a static object, which is allocated memory on the heap and hence it is guaranteed to have some space and

由于我们将const引用返回给obj,所以编译器会创建一个临时对象(针对某种nullObj ??)还是const引用充当nullPtr本身的别名?

Since we are returning const reference to obj, does compiler create a temporary object (to some kind of nullObj??) or Will the const reference act as an alias to nullPtr itself?

推荐答案

令我惊讶的是,没有人谈论引用何时可以指向空对象

I was surprised that no one talked about when reference can point to a null object

那是因为在正确的程序中无法实现.

That's because it can't, in a correct program.

您取消引用空指针的函数具有未定义行为.允许编译器发出例如在该点导致崩溃的代码.

Your function that dereferences a nullpointer has Undefined Behavior. The compiler is allowed to emit code that, for example, causes a crash at that point.

但是,UB的可能影响是该代码执行了人们认为会做的事情.因此,可能会发生空引用.我从未遇到过,但是如果您这样做,则意味着代码中存在严重的逻辑错误.

However, one possible effect of UB is that the code does what one thought it would do. So null-references can occur. I have never encountered one, but if you do, then it means that there is a serious logic error in the code.

您显示的所有对空对象引用函数的使用都是逻辑错误.

您最好将这些用法重新拼凑起来,并加以解决. ;-)

You'd better grep up those uses and fix things. ;-)

干杯hth.,

这篇关于指向空对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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