casting away const and then mutating

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Fri Jul 24 13:04:57 PDT 2015


On 07/24/2015 09:43 PM, Steven Schveighoffer wrote:
> On 7/24/15 3:02 PM, Timon Gehr wrote:
>> On 07/23/2015 10:20 PM, Steven Schveighoffer wrote:
>>> On 7/23/15 2:43 PM, anonymous wrote:
>>>> Steven disagrees and thinks that there are cases where it's ok. Namely,
>>>> this simple case would be ok:
>>>>
>>>> ----
>>>> int x;
>>>> const int *y = &x;
>>>> *(cast(int *)y) = 5;
>>>> ----
>>>
>>> Yes, IMO, this should simply work and be consistent. The compiler could
>>> use willful ignorance to assume x is still 0, but I find that to be
>>> counterproductive. It would have to implement flow analysis to determine
>>> that y must point at x, and then simply ignore the assignment during
>>> that analysis.
>>> ...
>>
>> No, it would be sufficient to have a simple form of constant propagation
>> to screw up here.
>
> What do you mean?
>
> -Steve

Assuming UB for modifying through a const reference, the compiler does 
not have to be clever at all to come up with the following semantics for 
that piece of code:

void main(){
     int x;
     const int* y=&x;
     *(cast(int*)y)=5;

     assert(x==0); // constant propagated
     assert(*y==5);
     assert(*&x==5);
}


More information about the Digitalmars-d mailing list