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

Alex Rønne Petersen xtzgzorex at gmail.com
Sun May 13 20:47:54 PDT 2012


On 14-05-2012 05:19, Jonathan M Davis wrote:
> 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.

Don't forget contracts. The this reference is now const inside those 
too. This can get painful sometimes when you really don't want the this 
reference to be const inside your invariants. With 2.058, I had to 
insert a lot of cast()s to throw const away inside those. So... 
effectively, it's pretty hard to avoid const unless you don't use 
contracts at all.

>
> 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

It's kinda funny that something which on dlang.org's FAQ is described as 
a compiler optimization hint (http://dlang.org/const-faq.html#const) 
isn't useful at all for this purpose...

-- 
- Alex


More information about the Digitalmars-d mailing list