interface A { void f(); }
void f(A a)
{
if(a!=null)a=null;
}
Error: use '!is' instead of '!=' when comparing with null
Mother of god.
Comment #1 by schveiguy — 2016-03-13T16:43:13Z
Some backstory:
Originally, if a was actually null, this would cause a segfault (it would try to call a.opEquals(null), which was a virtual call, etc.). This is why the error was added -- any usage of != null for classes/interfaces was never what you really wanted.
But with the current way object comparisons are done, != null would do the correct thing. I think actually, we can remove the error completely.
Comment #2 by issues.dlang — 2016-03-14T14:20:20Z
It's still more efficient to use is null or !is null, and it's what code really should be doing, but making it an error to use == null or != null is arguably a bit much.
Comment #3 by dfj1esp02 — 2016-03-14T14:47:40Z
In reality I'm comparing COM interfaces. I removed the check, it was defensive anyway. That's my concern actually: such checks should be a no-brainer or it will cause very nasty consequences in the long run, so yeah, it's disturbing.
Comment #4 by issues.dlang — 2016-03-14T16:28:12Z
At this point, comparing null objects will work just fine, since the free function opEquals that calls the member function opEquals for classes checks for null first, but if you use is, you skip the call to opEquals entirely. So, the error is arguably forcing you to follow best practices, but if the error weren't there, the code would work just fine. It would just be slightly less efficient.
Comment #5 by dfj1esp02 — 2016-03-15T13:39:46Z
The problem is not best practices, but usability.
Comment #6 by schveiguy — 2016-03-15T14:19:46Z
lowering != null to !is null is the right answer. I would be surprised if inlining doesn't automatically do this. But of course, the compiler rejects it, so no way to test it.
Comment #7 by issues.dlang — 2016-03-15T15:45:11Z
> The problem is not best practices, but usability.
As I said, while it's best practice to use is and !is with null, it is a bit much to treat it as an error to use == or !=. So, I'm not opposed to it being changed. I'm just pointing out that what it's telling you to do is what you really should be doing anyway. It's just being too forceful about it.
> lowering != null to !is null is the right answer.
That would be a good approach.
Comment #8 by dfj1esp02 — 2016-03-16T13:54:38Z
A little comparison: in java and C# Object.Equals is provided, but not called implicitly. It's provided, but is opt-in and explicit, it's all somewhat rooted in java, C# and D just copied it. C# uses C++-style operator overloads, it's up to them to call Object.Equals or not. Also C# requires x.Equals(null) to always return false.
(In reply to Steven Schveighoffer from comment #6)
> lowering != null to !is null is the right answer.
That would be awesome.
Comment #9 by robert.schadek — 2024-12-13T18:47:07Z