const
Michel Fortin
michel.fortin at michelf.com
Sun Mar 30 05:00:49 PDT 2008
On 2008-03-29 01:07:44 -0400, Benji Smith <benji at benjismith.net> said:
> I suppose in D, I'd have to avoid declaring vectors as const. Which
> would be a shame, because the basic data in the structure is never
> modified after construction. The only thing that *ever* changes is
> those values that are lazily evaluated and then memoized.
I think the idea here is that your vector class shouldn't be const, but
your vector data inside the vector class could be const or invariant.
Something like this:
class Vector {
invariant(VectorData) data;
CalculationCache cache;
/* accessors */
}
If you create a constant Vector then you can't change the cached
values, but that's just asserting the reality: your Vector object isn't
constant if its cache isn't and the compiler cannot make optimizations
by assuming constancy of the Vector object. In my example above, the
vector's data is invariant though, and calculating things using this
data may benefit from automatic optimizations for invariant data (like
pararalelizing, when the compiler supports that).
So, despite sharing the same keyword, D const isn't a logical const
like in C++, it's an optimization-enabling const for the compiler. This
means that by making some of your member functions const, you're
commiting to a particular implementation of your class or struct where
you guarenty you're not changing any bit in it, so you should probably
not add const everywhere it seems "logical", like in C++.
--
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/
More information about the Digitalmars-d
mailing list