invariant/const class storage class
Steven Schveighoffer
schveiguy at yahoo.com
Wed Oct 1 10:41:29 PDT 2008
"Sean Kelly" wrote
> Yigal Chripun wrote:
>> Walter Bright wrote:
>>> Simen Kjaeraas wrote:
>>>> Is this really correct behavior? How then are we supposed to
>>>> initialize our
>>>> invariant objects?
>>> Currently, create them as mutable ones, then cast them to invariant.
>>
>> I understand casting as breaking the type system. shouldn't there be a
>> way to create invariant objects without the cast?
>> an invariant constructor seems a good way to solve this. any plans on
>> adding such a feature to D2?
>
> Definitely. I can't imagine that the current situation is any more than
> an incomplete design. After all, everything needs to be initialized.
>
>> I think it can work like this:
>>
>> class A {
>> this(params) {} // [1]
>> invariant this(params) {} // [2]
>> }
>
> I don't see any point in having a separate 'invariant' ctor, given my
> point about initialization above. It should be perfectly legal to simply
> do:
>
> class A {}
> invariant a = new A;
>
> Just as it should be legal to do:
>
> string s = "a" ~ "b";
>
> That both are illegal right now is ridiculous. Perhaps the "Polysemous
> Value" idea can apply here. Since the compiler can clearly detect that in
> both cases the value being assigned is not shared it should be perfectly
> acceptable to implicitly convert its type to a compatible but stronger
> type.
What if the constructor for A stores a mutable reference to itself
somewhere? Or even a mutable reference to one of it's members? This breaks
the guarantee of transitive invariance, and the author of the constructor
shouldn't need to worry about that. That's why I think we do need invariant
constructors.
BTW, I think you may have mistyped your string s = "a" ~ "b" example, that
should be legal.
-Steve
More information about the Digitalmars-d
mailing list