D const design rationale

Don Clugston dac at nospam.com.au
Fri Jun 22 05:17:39 PDT 2007


Deewiant wrote:
> Don Clugston wrote:
>> QUOTE ----
>> int x = 3;
>> const int *p = &x;
>> *p = 4;        // error, read-only view
>> x = 5;        // ok
>> int y = *p;    // y is set to 5
>>
>> This is one instance of the so-called aliasing problem, since while the
>> above snippet is trivial, the existence of such aliases can be very hard
>> to detect in a complex program. It is impossible for the compiler to
>> reliably detect it. This means that the compiler cannot cache 4 in a
>> register and reuse the cached value to replace *p, it must go back and
>> actually dereference p again.
>> ---
>> Shouldn't that be: "the compiler cannot cache 3 in a register" ?
> 
> No. At "*p = 4;" the compiler can't cache 4, because then at "int y = *p;" y
> would become 4 instead of 5.
> 
> Although in the example it's moot because "*p = 4;" is an error.
In which case the example doesn't demonstrate anything. <g>

Better, I think, would be:
int x = 3;
const int *p = &x;
*p = 4;        // error, read-only view
int y = *p;
x=5;
int z = *p;

and then compiler can't set z=y.
Then we can see what invariant is for:

int x = 3;
invariant int *p = &x; // error, x is not invariant


invariant int x = 3;
invariant int *p = &x;
*p = 4;        // error, p is invariant
int y = *p;
x=5;           // error, x is invariant
int z = *p;
// compiler knows that y==z.



More information about the Digitalmars-d mailing list