Checking if this is null(检查这是否为空)
问题描述
检查 this 是否为空是否有意义?
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.
如果 this 为 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).
请注意,这也适用于非虚拟函数.
Note that this holds true for non-virtual functions as well.
一些实现允许 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.
这篇关于检查这是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查这是否为空
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07