I just got it! (invariant/const)
Steven Schveighoffer
schveiguy at yahoo.com
Wed Apr 9 09:58:07 PDT 2008
"Georg Wrede" wrote
> Janice Caron wrote:
>> On 09/04/2008, Denton Cockburn wrote:
>>
>>> > Of course, the explicit cast necessary to
>>> > create an invariant C in the first place is a bit ugly. Maybe we need
>>> > "inew" to make new invariant objects?
>>>
>>>Couldn't the compiler insert the cast based on the declaration?
>>
>>
>> No, because objects created by new are not necessarily transitively
>> unique. For example
>>
>> class C
>> {
>> int * p;
>>
>> this()
>> {
>> p = &someGlobalVariable;
>> }
>> }
>>
>> invariant C c = cast(invariant) new C;
>> someGlobalVariable = 1;
>>
>> Whoops! c just changed!
>>
>> The explicit cast makes it the programmer's fault, not the compiler's!
>>
>> Come to think of it, "inew" would suffer the exact same problem, so it
>> doesn't solve anything. Looks like there's no easy way to make an
>> invariant class instance.
>
> It should be illegal to cast objects invariant unless the compiler can
> guarantee the invariantness. So the cast here should produce an error.
This cannot be guaranteed by the compiler. It is depending on you to ensure
that the object stays invariant. From
http://www.digitalmars.com/d/2.0/const3.html
"The second way (to create invariant data) is to cast data to invariant.
When doing so, it is up to the programmer to ensure that no other mutable
references to the same data exist."
-Steve
More information about the Digitalmars-d
mailing list