Getting the const-correctness of Object sorted once and for all

Jonathan M Davis jmdavisProg at gmx.com
Sun May 13 20:19:36 PDT 2012


On Monday, May 14, 2012 05:09:28 Era Scarecrow wrote:
> On Monday, 14 May 2012 at 02:57:57 UTC, Mehrdad wrote:
> > On Monday, 14 May 2012 at 02:48:20 UTC, Jonathan M Davis wrote:
> >> But that's just one of the costs of const in D.
> > 
> > The problem is that it's unavoidable.
> > 
> > I.e. you can't say "don't Mark it as const if it isn't const",
> > because, practically speaking, it's being forced onto the
> > programmers by the language.
> 
>   With const and immutable being transitive, there are cases when
> there's things you want to do with an object after you've made it
> and it's in a const structure. I know I've made a struct that was
> intended to hold immutable data, however it refused to allow
> methods to until const was appended to the signatures of the
> functions. At first it was annoying; But when I see bigger
> picture of why it makes much more sense.
> 
>   Nothing we make 'has' to have const on it but inevitably they
> may be used in a read-only way. I'm trying to think of it as my
> structs and classes being as const-friendly as possible in those
> cases.

In general, you _can_ avoid const completely if you want to. However, with 
opEquals, opCmp, toHash, and toString being const @safe pure nothrow, you 
_can't_ avoid it completely - at least not entirely cleanly.

You could have non-const overloads which did what you wanted and make the 
normal const ones assert(0) if they're called. But you're basically forced to 
work around const in this case. This is in definite contrast to C++ where you 
_can_ avoid const completely if you want to.

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.

- Jonathan M Davis


More information about the Digitalmars-d mailing list