Consequences of casting away immutable from pointers

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Jan 5 18:13:11 UTC 2018


On Fri, Jan 05, 2018 at 05:50:34PM +0000, jmh530 via Digitalmars-d-learn wrote:
> On Friday, 5 January 2018 at 04:10:54 UTC, Steven Schveighoffer wrote:
> > 
> > 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.
> > 
> > -Steve
> 
> I also checked that if you create an instance of a class on the heap
> with an immutable constructor, then it's no longer in the register.
> Thus, I can now modify the immutable object from the pointer that I
> casted away immutable (though not that I would!)

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


T

-- 
Береги платье снову, а здоровье смолоду. 


More information about the Digitalmars-d-learn mailing list