检查这是否为null [英] Checking if this is null

查看:192
本文介绍了检查这是否为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查是否为null是否有意义?

Does it ever make sense to check if this is null?

说我有一个类有方法;在这个方法中,我检查 this == NULL ,如果是,返回一个错误代码。

Say I have a class with a method; inside that method, I check this == NULL, and if it is, return an error code.

为null,则表示对象已删除。该方法是否能够返回任何内容?

If this is null, then that means the object is deleted. Is the method even able to return anything?

更新:我忘了提及该方法可以从多个线程调用,

Update: I forgot to mention that the method can be called from multiple threads and it may cause the object to be deleted while another thread is inside the method.

推荐答案


是否有意义检查this == null?

Does it ever make sense to check for this==null? I found this while doing a code review.

在标准C ++中,它没有,因为对空指针的任何调用都是未定义的行为,所以任何依赖这种检查的代码都是非标准的(不能保证检查甚至会被执行)。

In standard C++, it does not, because any call on a null pointer is already undefined behavior, so any code relying on such checks is non-standard (there's no guarantee that the check will even be executed).

注意这对于非虚拟

然而,一些实现允许 this == 0 ,因此为那些实现专门编写的库有时会使用它作为一个黑客。这样的对的一个很好的例子是VC ++和MFC - 我不记得确切的代码,但我清楚地记得看到 if(this == NULL)检查MFC源

Some implementations permit this==0, however, and consequently libraries written specifically for those implementations will sometimes use it as a hack. A good example of such a pair is VC++ and MFC - I don't recall the exact code, but I distinctly remember seeing if (this == NULL) checks in MFC source code somewhere.

它也可以作为一个调试辅助,因为在过去的某些时候,这个代码被击中 this == 0 是因为调用者有错误,所以插入一个检查以捕获未来的实例。

It may also be there as a debugging aid, because at some point in the past this code was hit with this==0 because of a mistake in the caller, so a check was inserted to catch future instances of that. An assert would make more sense for such things, though.


如果this = null,那么表示该对象被删除。

If this == null then that means the object is deleted.

不,这并不意味着。这意味着对空指针或从空指针获得的引用调用了一个方法(尽管获得这样的引用已经是U.B.)。这与 delete无关,并且不需要此类型的任何对象曾经存在过。

No, it doesn't mean that. It means that a method was called on a null pointer, or on a reference obtained from a null pointer (though obtaining such a reference is already U.B.). This has nothing to do with delete, and does not require any objects of this type to have ever existed.

这篇关于检查这是否为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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