On Wednesday, 13 July 2016 at 11:28:11 UTC, Andrei Alexandrescu wrote:
On 7/13/16 5:19 AM, John Colvin wrote:
"Casting away immutable is undefined behaviour": the following code has
undefined results (note, not implementation defined, not
if-you-know-what-you're-doing defined, undefined), despite not doing
anything much:

void foo()
{
    immutable a = new int;
    auto b = cast(int*)a;
}

"modifying immutable data is undefined": The above code is fine, but the
following is still undefined:

void foo()
{
    immutable a = new int;
    auto b = cast(int*)a;
    b = 3;
}

Interesting distinction. We must render the latter undefined but not the former. Consider:

struct S { immutable int a; int b; }
S s;
immutable int* p = &s.a;

It may be the case that you need to get to s.b (and change it) when all you have is p, which is a pointer to s.a. This is essentially what makes AffixAllocator work.


Andrei

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.

Reply via email to