compare struct with string member is wield;

Dmitry Olshansky dmitry.olsh at gmail.com
Wed Oct 12 05:16:13 PDT 2011


On 12.10.2011 10:14, Jonathan M Davis wrote:
> On Wednesday, October 12, 2011 06:07:38 Cheng Wei wrote:
>> Sorry. The previous is not the one causes the problem.
>> Try this:
>>
>> struct S {
>>      string str = "Hello";   // Adding an initial value here.
>> };
>>
>> S g_s;
>>
>> unittest {
>>      S s1;
>>      S s2;
>>      assert(s1 == s2); // Success
>>      assert(g_s == s1); // Fail
>>      auto s3 = g_s;
>>      assert(s3 == g_s);; // Even this will fail.
>> }
>>
>> It seems if the string is initialized with a default value, then this
>> does not work.
>
> Yeah. It's failing for me too. It's obviously a bug of some kind. I'd have to
> going digging through d.puremagic.com/issues to see whether anything like it
> has been reported though.
>
> By the way, the semicolon at the end of the definition of S is unnecessary in
> D.
>
> - Jonathan M Davis

It is strange. The reason could be: by default for structs it does 
bitlevel memcmp style comparison. Now in this case it will compare 
pointer-length pairs directly, if somehow global var got different 
string (address-wise) then it won't compare equal to S.init no matter what.

So two things:
- print out .str.ptr  for all of you vars to see if that's the case
- define sane opEquals*:
	bool opEquals(in S s)const{
		return str == t.str;
	}

* I haven't followed the timeline of the changes to opEquals that 
ultimately made things much simpler so you may have to rewrite it as 
bool opEquals(const ref S s)const in dmd 2.055.

-- 
Dmitry Olshansky


More information about the Digitalmars-d-learn mailing list