Actual immutability enforcement by placing immutable data into read-only sections
Siarhei Siamashka
siarhei.siamashka at gmail.com
Mon Dec 19 17:50:03 UTC 2022
On Monday, 19 December 2022 at 15:34:35 UTC, bauss wrote:
> On Monday, 19 December 2022 at 15:25:17 UTC, IGotD- wrote:
>> [...]
>> 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:
>
> ```D
> 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.
The compiler will reject your constructor if you change
"immutable int a;" to "immutable int a = 2030;":
test.d(8): Error: cannot modify `immutable` expression `a`
If a variable is both declared and initialized simultaneously,
then it's probably safe to be placed into a read-only section.
Please correct me if I'm wrong.
More information about the Digitalmars-d
mailing list