Consequences of casting away immutable from pointers
Patrick Schluter
Patrick.Schluter at bbox.fr
Fri Jan 5 18:40:12 UTC 2018
On Friday, 5 January 2018 at 18:13:11 UTC, H. S. Teoh wrote:
> On Fri, Jan 05, 2018 at 05:50:34PM +0000, jmh530 via
> Digitalmars-d-learn wrote:
>
> Be careful with that:
>
> class C { int x; }
> immutable C c = new C(5);
> auto i = c.x;
>
> C y = cast(C) c;
> y.x = 10;
> i = c.x; // <-- compiler may assume c.x is still 5
>
> Since c.x is read from an immutable object, the compiler may
> assume that its value hasn't changed the second time you access
> it, so it may just elide the second assignment to i completely,
> thereby introducing a bug into the code.
>
> Basically, casting away immutable is UB, and playing with UB is
> playing with fire. :-P
>
And these things are nasty. We had one in our C project last
month that had us tear our hair out. It was in the end a
documentation problem of gcc that induced the misunderstanding
of the purpose of __attribut__((malloc)) and its effect on
aliased pointer.
More information about the Digitalmars-d-learn
mailing list