Let's not make invariants const

deadalnix deadalnix at gmail.com
Sat Aug 4 01:37:55 PDT 2012


Le 03/08/2012 21:19, Alex Rønne Petersen a écrit :
> Hi,
>
> This:
>
> $ cat test.d
> class A
> {
> int i;
>
> invariant()
> {
> i = 42;
> }
> }
>
> Currently doesn't compile:
>
> $ dmd test.d
> test.d(7): Error: can only initialize const member i inside constructor
>
> (Obviously this example is silly, but it's just meant to illustrate the
> point of this thread.)
>
> I believe this behavior is too strict. I don't agree that the language
> should dictate what *my* invariant can and cannot do. Not to mention
> that the standard library is far from const-friendly enough for this
> strictness to be practically reasonable today (I have tons of cast()s in
> my programs today due to this - not cool).
>
> Does anyone else find this behavior too strict?
>

I don't.

Actually, it save from many mistakes. You are always free to cast away 
const. This is unsafe, but you are in an invariant and aren't supposed 
to do non const operation. At the end, this is fair.

As usual, a safe behavior is proposed, and ways exists to free yourself 
from safety. This is Dish.

You mention a good point when saying that a lot of lib isn't const 
friendly and this is true. The problem don't lie into invariant and 
constness but here.


More information about the Digitalmars-d mailing list