Consequences of casting away immutable from pointers

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Jan 5 04:24:47 UTC 2018


On Thursday, January 04, 2018 23:10:54 Steven Schveighoffer via Digitalmars-
d-learn wrote:
> On 1/4/18 10:58 PM, jmh530 wrote:
> > 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?
>
> Yes, this is undefined behavior.
>
> https://dlang.org/spec/const3.html#removing_with_cast
>
> The compiler assumes x is going to be 5 forever, so instead of loading
> the value at that address, it just loads 5 into a register (or maybe it
> just folds x == 5 into true).
>
> The compiler would likely be free to assume *p_x == 5 forever also, if
> it was clever enough.
>
> I'd recommend not doing this.

Yeah, casting away either const or immutable is just begging for trouble,
though it's likely to be worse with immutable, since there are more
optimizations that the compiler can do based on immutable. D's const and
immutable are definitely not the same as C++'s const and treating either of
them like they have backdoors is just going to cause bugs. If you ever need
a backdoor to get around them, then you shouldn't be using them.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list