检查这是否为空
检查 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.
相关文章