On Wednesday, 13 July 2016 at 11:48:15 UTC, John Colvin wrote:
Hmm. You have to create a mutable reference to immutable data
to do that (although you are casting away immutable). Let's
consider this:
*(p + 1) = 3;
it either has to be written like this:
*((cast(int*)p) + 1) = 3;
or like this:
*(cast(int*)(p + 1)) = 3;
The first is creating a mutable pointer to immutable data, the
second creates an immutable pointer to mutable data. I'm not
sure which is worse, considering that those reference could sit
around for ages and be passed around etc., e.g.
auto tmp = p + 1;
// ... do loads of stuff, possibly reading from tmp
*(cast(int*)tmp) = 3;
seems like we would end up in trouble (either of our own
creation or via the optimiser) from thinking tmp actually
pointed to immutable data. Probably worse than a mutable
reference to immutable data, as long as you didn't write to it.
Pointer arithmetic in objects is really quite dangerous w.r.t.
immutability/const.
immutable int* p = ...
auto cp = cast(const int*)p; // cast immutable* to const*
auto cq = p + 1 // shift const* from immutable data
to mutable data
auto q = cast(int*) cq; // cast const* to mutable*
*q = 3;
This way both temporaries are const, and can point to both
mutable and immutable.
So you never use immutable pointers to mutable data nor mutable
pointers to immutable data.