Object.toString, toHash, opCmp, opEquals

Dennis dkorpel at gmail.com
Fri Apr 26 21:38:28 UTC 2024


On Friday, 26 April 2024 at 20:17:09 UTC, Walter Bright wrote:
> Mutating toString, toHash, opCmp, and opEquals is unusual 
> behavior, which is why const should be the default for them. 
> After all, who expects a==b to change a or b?

Timon has mentioned data structures with amortized time 
complexity several times now, but perhaps an example closer to 
home helps:

https://github.com/dlang/dmd/blob/9ffa763540e16228138b44c3731d9edc2a7728b6/compiler/src/dmd/dsymbol.d#L668

In this case, `toString` (or `toPrettyChars`, same idea) is 
*logically* const because it doesn't mutate the Dsymbol 
meaningfully, but it can't be D's *memory* const because it does 
change a class field to store a cached result.



More information about the Digitalmars-d mailing list