Can't use toHexString

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 19 05:08:16 PDT 2015


This line is illegal:

> return toHexString!(Order.decreasing)(crc.finish());

The std.digest.toHexString and variants return a *static array* 
which is static data and has a scope lifetime.

It is horrendous a compiler bug that allows it to implicitly 
convert to string - it should not compile because it silently 
gives bad results, escaping a reference to temporary memory while 
claiming it is immutable.

Confusingly though, this line is fine:

> return crcHexString(crc.finish());

It is an EXTREMELY subtle difference in the function signature 
(and totally bug prone, yet the documentation doesn't call it 
out...)

http://dlang.org/phobos/std_digest_digest.html#.toHexString


Notice the first overload there returns a static array, 
char[num*2], two of them return `auto`, so who knows what the 
hell they do.... and one actually returns `string`.

Slightly different arguments will give you wildly different 
results.



The safest thing to do is to `import std.conv;` and always 
`to!string` any of those *HexString return values if you want to 
return them like this.

Or you could also keep them in a local variable and use them 
before the function returns, then the stack allocated static 
array is OK too.


More information about the Digitalmars-d-learn mailing list