Inherited const when you need to mutate
Jonathan M Davis
jmdavisProg at gmx.com
Mon Jul 9 10:36:16 PDT 2012
On Monday, July 09, 2012 18:34:14 David Piepgrass wrote:
> I guess D does not have 'mutable' (like C++) to override const on
> methods?
No, const is actually const. You can't modify anything which is const through
that reference (or pointer) to that data. Casting away const and mutating
something is undefined behavior. This provides much stronger guarantees and
better enables compiler optimizations. More importantly, it's required for
immutabel, since a const variable could actually be immutable underneath, in
which case, depending on how it was constructed (e.g. it was put in ROM), it
could result in a segfault if you tried to mutate it after casting away const.
http://stackoverflow.com/questions/4219600/logical-const-in-d
So, const gives you much greater benefits in D than in C++, but it also comes
at a much higher cost. And it comes to a bit of a head in Object, because
certain function _must_ be const in Object in order to work with const (namely
opEquals, opCmp, toHash, and toString), but they _can't_ be const for certain
schemes (e.g. caching) to work. The open question is how to fix this (or if it
even can be fixed). But the current plan is to make all 4 of those functions be
@safe pure const nothrow, and that _will_ make certain schemes effectively
infeasible.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list