default '==' on structs

spir denis.spir at gmail.com
Wed Feb 2 08:35:50 PST 2011


On 02/02/2011 04:20 PM, Lars T. Kyllingstad wrote:
> On Wed, 02 Feb 2011 15:55:53 +0100, spir wrote:
>
>> Hello,
>>
>> What are the default semantics for '==' on structs?
>>
>> I ask this because I was forced to write opEquals on a struct to get
>> expected behaviour. This struct is basically:
>>
>> struct Lexeme {
>>       string tag;
>>       string slice;
>>       Ordinal index;
>> }
>>
>> Equal Lexeme's compare unequal using default '=='. When I add:
>>
>>       const bool opEquals (ref const(Lexeme) l) {
>>           return (
>>                  this.tag   == l.tag
>>               && this.slice == l.slice
>>               && this.index == l.index
>>           );
>>       }
>>
>> then all works fine. What do I miss?
>
> I think the compiler does a bitwise comparison in this case, meaning that
> it compares the arrays' pointers instead of their data.  Related bug
> report:
>
>    http://d.puremagic.com/issues/show_bug.cgi?id=3433
>
> -Lars

Thank you, Lars.
In fact, I do not really understand what you mean. But it helped me think 
further :-)
Two points:

* The issue reported is about '==' on structs not using member opEquals when 
defined, instead performing bitwise comparison. This is not my case: Lexeme 
members are plain strings and an uint. They should just be compared as is. 
Bitwise comparison should just work fine.
Also, this issue is marked solved for dmd 2.037 (I use 2.051).

* The following works as expected:

struct Floats {float f1, f2;}
struct Strings {string s1, s2;}
struct Lexeme {
     string tag;
     string slice;
     uint index;
}

unittest {
     assert ( Floats(1.1,2.2)  == Floats(1.1,2.2) );
     assert ( Strings("a","b") == Strings("a","b") );
     assert ( Lexeme("a","b",1) == Lexeme("a","b",1) );
}

This shows, if I'm right:
1. Array (string) members are compared by value, not by ref/pointer.
2. Comparing Lexeme's works in this test case.

* Why does my app then need opEquals, just to compare member per member (see 
code above)?
The issue happens in a unittest. Lexemes are generated by a typical use of the 
module's features, then assert() compares them to expected result:
	assert ( lexeme == Lexeme(expected_data) );
I'll try to reduce the issue to isolate the key point.

Thank you for your help,
denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list