Object.opEquals, opCmp, toHash
Stewart Gordon
smjg_1998 at yahoo.com
Thu Feb 16 09:28:47 PST 2012
On 16/02/2012 13:05, bearophile wrote:
> Stewart Gordon:
>
>> But if the method is pure, the compiler can automatically implement this as an optimisation.
>
> Functions like toHash take nothing and return a single size_t (hash_t). Often you want
> to compute the hash value lazily, but this is not possible if toHash needs to be pure.
Hence my point. The laziness could be implemented on the compiler side, thereby bypassing
the contracts of purity and constancy.
For example, if the source code is
string toString() const pure {
return ...;
}
then the compiler would generate code equivalent to
bool _has_cached_toString;
string _cached_toString;
string toString() {
if (!_has_cached_toString) {
_cached_toString = ...;
_has_cached_toString = true;
}
return _cached_toString;
}
and moreover, clear the _has_cached_toString flag whenever any of the members on which the
cached value depends is changed.
> A explicit optional @memoize annotation (similar to the std.functional.memoize) allows
toHash to be both catching and safe. (I was also thinking about the idea of a
@trusted_pure, but I don't like it, and I think it causes chaos).
>
> Bye,
> bearophile
More information about the Digitalmars-d
mailing list