On Thu, Sep 02, 2021 at 05:17:15PM +0000, DLearner via Digitalmars-d-learn 
wrote:
[...]
> The following clean-compiled and produced the expected result:
> ```
>     ubyte[10] Arr;
> 
>     immutable void* ArrPtr;
>       shared static this() {
>               ArrPtr = cast(immutable void*)(&Arr[0]);
>       }

Casting this to immutable is unsafe, because Arr is actually mutable. In
D, const and immutable are transitive, so when you cast a pointer into
immutable, you're basically promising that *both* the pointer *and* the
data pointed to will never change. The compiler is free to assume that
the data pointed to will never change, which may cause consistency
problems if the data *does* change later.

In cases like this, const is a better choice: const ensures that the
pointer will not mutate and the pointed-to data cannot be mutated
through this pointer, but the data *may* be mutated through another
reference (e.g., by modifying Arr directly).


[...]
> I am looking for a mutable Arr but would like an immutable ArrPtr.

In D, const and immutable are transitive, so you cannot do this (but see
below).


> ```
> `Arr` is not immutable, so `ArrPtr` shouldn't point at it if it's
> immutable.
> ```
> Surely there is no inconsistency - at run time the array is in a fixed
> place,  so ArrPtr is (or at least should be) a constant, but the
> contents of the array can vary as the program runs.

In this case, what you want is const, not immutable.  Const means you
cannot modify the pointer, and you cannot mutate the data through this
pointer, but you *can* modify the array from a mutable reference.


T

-- 
You are only young once, but you can stay immature indefinitely. -- azephrahel

Reply via email to