Actual immutability enforcement by placing immutable data into read-only sections

bauss jacobbauss at gmail.com
Mon Dec 19 15:34:35 UTC 2022


On Monday, 19 December 2022 at 15:25:17 UTC, IGotD- wrote:
> On Monday, 19 December 2022 at 14:07:49 UTC, bauss wrote:
>>
>> Of course literals can be placed in read-only and should be, 
>> so in that case I think this would be good, BUT I don't think 
>> it's possible to really do for __all__ immutable data.
>
> https://dlang.org/articles/const-faq.html
>
> *What is immutable good for?*
>
> *Immutable data, once initialized, is never changed. This has 
> many uses:*
>
> - *Access to immutable data need not be synchronized when 
> multiple threads read it.*
> - *Data races, tearing, sequential consistency, and cache 
> consistency are all non-issues when working with immutable 
> data.*
> - *When doing a deep copy of a data structure, the immutable 
> portions need not be copied.
> - Invariance allows a large chunk of data to be treated as a 
> value type even if it is passed around by reference (strings 
> are the most common case of this).*
> - *Immutable types provide more self-documenting information to 
> the programmer.*
> - ***Immutable data can be placed in hardware protected 
> read-only memory, or even in ROMs.***
> - *If immutable data does change, it is a sure sign of a memory 
> corruption bug, and it is possible to automatically check for 
> such data integrity.*
> - *Immutable types provide for many program optimization 
> opportunities.*
>
> *const acts as a bridge between the mutable and immutable 
> worlds, so a single function can be used to accept both types 
> of arguments.*
>
>
> I always interpreted immutable as something that must be 
> constructed during compile time and put in the RO section of 
> the program.

Yes, but it's not the reality. Immutable data can be constructed 
at runtime and it happens all the time in shared static 
constructors etc. I think it would be a too big breaking change 
that you suddenly can't do that anymore.

Ex. the following program is valid:

```
import std.stdio : writeln;
import std.datetime : Clock;

immutable int a;

shared static this()
{
     a = Clock.currTime().year;
}

void main()
{
     writeln(a);
}
```

In the above example "a" cannot be placed in read-only memory.

Of course my example isn't something you would do in an every day 
program, BUT it could be substituted for values loaded from a 
file etc.


More information about the Digitalmars-d mailing list