www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - this compare not using opCmp?

reply "Era Scarecrow" <rtcvb32 yahoo.com> writes:
  In some code I'm working on, my asserted when I've confirmed it 
was correct. With the opCmp() overridden.  'this' refers to the 
current object, so why doesn't the first one succeed?

class X {
   int z;

   this(int xx) {
	z = xx;
   }

   override int opCmp(Object y){
	X x = cast(X) y;
	return z - x.z;
   }

   void something(X rhs) {
     assert(this.opCmp(rhs) == 0); //works fine.
     assert(this == rhs); 	  //fails?
   }
}

int main(){
	X a = new X(10);
	X b = new X(10); //different objects, same compare value
	a.something(b);
	return 0;
}
Apr 29 2012
next sibling parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Monday, April 30, 2012 07:09:46 Era Scarecrow wrote:
   In some code I'm working on, my asserted when I've confirmed it
 was correct. With the opCmp() overridden.  'this' refers to the
 current object, so why doesn't the first one succeed?
 
 class X {
    int z;
 
    this(int xx) {
 	z = xx;
    }
 
    override int opCmp(Object y){
 	X x = cast(X) y;
 	return z - x.z;
    }
 
    void something(X rhs) {
      assert(this.opCmp(rhs) == 0); //works fine.
      assert(this == rhs); 	  //fails?
    }
 }
 
 int main(){
 	X a = new X(10);
 	X b = new X(10); //different objects, same compare value
 	a.something(b);
 	return 0;
 }

== uses opEquals, not opCmp. It's using Object's opEquals, which does a comparison of the references, so it's true when comparing the exact same object and false otherwise. - Jonathan M Davis
Apr 29 2012
prev sibling next sibling parent "Era Scarecrow" <rtcvb32 yahoo.com> writes:
On Monday, 30 April 2012 at 05:22:56 UTC, Jonathan M Davis wrote:
 == uses opEquals, not opCmp. It's using Object's opEquals, 
 which does a
 comparison of the references, so it's true when comparing the 
 exact same
 object and false otherwise.

Ahhh of course. Personally I think opCmp includes opEquals... At least I only have to deal with 2 compare functions and not more.
Apr 29 2012
prev sibling parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Monday, April 30, 2012 07:28:16 Era Scarecrow wrote:
 On Monday, 30 April 2012 at 05:22:56 UTC, Jonathan M Davis wrote:
 == uses opEquals, not opCmp. It's using Object's opEquals,
 which does a
 comparison of the references, so it's true when comparing the
 exact same
 object and false otherwise.

Ahhh of course. Personally I think opCmp includes opEquals... At least I only have to deal with 2 compare functions and not more.

I believe that there are two major reasons why opEquals is separate: 1. Many types of objects can have equality but less than and greater than comparisons would make no sense for them. 2. It's more efficient to check for equality with opEquals than it would be with opCmp. - Jonathan M Davis
Apr 29 2012