On Friday, 18 May 2018 at 23:53:12 UTC, IntegratedDimensions wrote:
Why does D complain when using == to compare with null? Is there really any technical reason? if one just defines == null to is null then there should be no problem. It seems like a pedantic move by who ever implemented it and I'm hoping there is actually a good technical reason for it.

tldr: this error is outdated.

In the days of yore, "obj == null" would call "obj.opEquals(null)". Attempting to call a virtual method on a null object is a quick path to a segmentation fault. So "obj == null" would either yield false or crash your program.

Except it's worse than that; your opEquals method had to explicitly check for null. So if your class had a custom equality function, "obj == null" was probably going to segfault no matter what.

Because of this common source of errors, in DMD 2.012 (2008), we got an error only for the case of comparing with a literal null. (The compiler isn't a mind-reader; it doesn't know whether that variable will be null when that line of code executes.)

This still sucked, so in 2015 we got a runtime function to handle object equality:
https://github.com/dlang/druntime/blob/dff824eda422b1fcdde5f2fe53120fcd71733aaa/src/object.d#L140

But we haven't removed the error message.

It *is* faster to call "foo is null" than "foo == null", but I don't think that's particularly worth a compiler error. The compiler could just convert it to "is null" automatically in that case.

One casualty of the current state of affairs is that no object may compare equal to null.
  • is == IntegratedDimensions via Digitalmars-d-learn
    • Re: is == Uknown via Digitalmars-d-learn
      • Re: is == IntegratedDimensions via Digitalmars-d-learn
    • Re: is == Neia Neutuladh via Digitalmars-d-learn
      • Re: is == Jonathan M Davis via Digitalmars-d-learn
      • Re: is == Neia Neutuladh via Digitalmars-d-learn
        • Re: is == Jonathan M Davis via Digitalmars-d-learn
        • Re: is == Neia Neutuladh via Digitalmars-d-learn
          • Re: is == Jonathan M Davis via Digitalmars-d-learn
      • Re: is == Steven Schveighoffer via Digitalmars-d-learn
        • Re: is == Jonathan M Davis via Digitalmars-d-learn
        • Re: is == Steven Schveighoffer via Digitalmars-d-learn
          • Re: is == Jonathan M Davis via Digitalmars-d-learn
          • Re: is == Steven Schveighoffer via Digitalmars-d-learn

Reply via email to