Object.toString, toHash, opCmp, opEquals

Walter Bright newshound2 at digitalmars.com
Fri Apr 26 00:57:49 UTC 2024


On 4/25/2024 4:36 PM, Timon Gehr wrote:
>> Without the `const` annotations, the functions are not usable by `const` 
>> objects without doing an unsafe cast. This impairs anyone wanting to write 
>> const-correct code,
> 
> "const correctness" does not work in D because const
> 
> a) provides actual guarantees
> b) is transitive

It's not the C++ notion of const, sure. But the name still applies.

> It is fundamentally incompatible with many common patters of object-oriented and 
> other state abstraction. It is not even compatible with the range API. Uses of 
> `const` are niche. `const` is nice when it does work, but it's not something you 
> can impose on all code, particularly object-oriented code.

Why would anyone, for example, try to mutate a range when it is passed to one of 
these functions?


>> and also impedes use of `@live` functions.
>> ...
> 
> Perfect. I have no intention of using `@live` functions. I do not see their 
> utility.

The utility is being able to write borrow-checker style code, so you can avoid 
things like double frees.

As I recall, it was you that pointed out that reference counting can never be 
safe if two mutable pointers to the same ref counted object (one to the object, 
the other to its interior) were passed to a function. (Freeing the first can 
leave the second interior pointer pointing to a deleted object.) The entire ref 
counting scheme capsized because of this.

>> I recommend that everyone who has overloads of these functions, alter them to 
>> have the `const` signatures. This will future-proof them against any changes 
>> to Object's signatures.
> 
> I will not do that, because if it does not outright break my code (e.g. because 
> Phobos cannot support `const` ranges), it actually limits my options in the 
> future in a way that is entirely unnecessary.

Why would anyone need toHash(), toString(), opEquals() or opCmp() to mutate 
their data? Wouldn't that be quite surprising behavior?



More information about the Digitalmars-d mailing list