On Monday, 14 May 2012 at 03:19:57 UTC, Jonathan M Davis wrote:
But with the way const in D works, I suspect that the folks who are looking for absolutely every CPU cycle and want caching and lazy-loading in their types are going to avoid const as completely as possible and figure out how to work around it for those 4 functions, whereas in C++, they'd probably use const liberally and use mutable where necessary.>

Seems like perhaps the opposite approach (limited of course) could be taken. Assume a 'mutable' keyword was used, where in the case an object/struct was made const, it would allow you to break the const system only for that variable. Could work, assuming it's not accessing ROM or something.

struct A {
  string st;
  mutable uint hash; //always mutable

  uint toHash() {
    if (!hash)
      hash = st.toHash();
    return hash;
  }
}

unittest{
  A a = A("TEST");
  immutable A b = A("TEST");

  assert(a.toHash() == b.toHash());
}

But that seems like a badly done workaround, and if you really wanted the hash cached, you would have it calculated during construction before it was returned. Something like that is likely more trouble than it's worth, plus it would easily be abused.

Reply via email to