Run-time setting of immutable variable?

Steven Schveighoffer schveiguy at gmail.com
Thu Sep 2 16:46:46 UTC 2021


On 9/2/21 12:01 PM, DLearner wrote:
> Suppose there is a variable that is set once per run, and is (supposed) 
> never to be altered again.  However, the value to which it is set is not 
> known at compile time.
> Example below, variable is 'ArrPtr';
> ```
> ubyte[10] Arr;
> 
> // immutable void* ArrPtr;
> void* ArrPtr;
> 
> void main() {
> 
>     ArrPtr = cast(void*)Arr[0];
> 
> // <Lots of code depending on ArrPtr, but not supposed to modify ArrPtr>
> 
> }
> ```
> Is there a way of getting D to guarantee that ArrPtr is never modified 
> after
> ```
>     ArrPtr = cast(void*)Arr[0];
> ```]

You shouldn't be doing this. `Arr` is not immutable, so `ArrPtr` 
shouldn't point at it if it's immutable.

If you want to guarantee that `ArrPtr` never changes once set, yet still 
want it to point at mutable data, you need to use a type that does that 
(like a head mutable or "write once" type), which I believe doesn't 
exist in phobos.

If you don't actually need to mutate the data via `ArrPtr`, you can make 
it const, and use H.S. Teoh's solution. But you should not use 
immutable, as the compiler implies that data pointed at is also 
immutable (and of course, you won't need casting). Make sure you use 
regular `static this`, not `shared static this`, as your fields are 
thread-local, not shared.

-Steve


More information about the Digitalmars-d-learn mailing list