interface opEquals

Antonio antoniocabreraperez at gmail.com
Fri Nov 24 17:39:10 UTC 2023


On Thursday, 23 November 2023 at 21:52:56 UTC, Jonathan M Davis 
wrote:

> I'd have to take the time to study your code in detail to see 
> whether what exactly you're seeing makes sense or not ...


My apologies... I should have proposed a more specific example.

```d
interface IOpt {  bool opEquals(IOpt other) const @safe pure;  }

class None : IOpt { bool opEquals(IOpt other) const @safe pure => 
true; }

void main() {
   None
     a = new None(),
     b = new None();

   IOpt
     a2 = a,
     b2 = b;

   assert(a == b);
   assert(a2 == a);
   assert(b2 == b);
   assert(a2 == b2); // fails!!!
}

```

>
> == on classes results in the free function, opEquals, in 
> object.d being called. That function does a variety of checks 
> such as checking whether either reference is null (to avoid 
> dereferencing null) and using is to compare the address of the 
> class references first (to avoid calling the class' opEquals if 
> both references are to the same object). It also makes sure 
> that both rhs.opEquals(lhs) and lhs.opEquals(rhs) are true for 
> == to be true to avoid subtle bugs that can come into play when 
> comparing a base class against a derived class.
>
> https://github.com/dlang/dmd/blob/master/druntime/src/object.d#L269
>

Replacing ```interface``` by ```abstract class``` removes the 
problem.  But I have not enough D knowledge to discover why 
interface version is not working


Thanks
Antonio





More information about the Digitalmars-d-learn mailing list