Consequences of casting away immutable from pointers
jmh530
john.michael.hall at gmail.com
Fri Jan 5 03:58:58 UTC 2018
I'm trying to understand the consequences of casting away
immutable from a pointer. The code below has some weird things
going on like the pointers still point to the correct address but
when you dereference them they don't point to the correct value
anymore.
Should I just assume this is undefined behavior and not bother
with it? Or is there a use case for this?
void main()
{
immutable(int) x = 5;
auto p_x = &x;
int* p_x_alt = cast(int*)p_x;
(*p_x_alt)++;
//addresses remain unchanged
assert(&x == p_x);
assert(p_x == p_x_alt);
assert(*p_x_alt == 6);
assert(*p_x == *p_x_alt); //but p_x and p_x_alt point to same
value
assert(x != *p_x); //yet that is not the case for x
assert(x == 5); //which still is 5
}
More information about the Digitalmars-d-learn
mailing list