Programming in D, page 155. shared static this() fails
Brother Bill
brotherbill at mail.com
Tue Jul 29 23:18:18 UTC 2025
On Tuesday, 29 July 2025 at 23:03:41 UTC, monkyyy wrote:
> On Tuesday, 29 July 2025 at 22:57:50 UTC, Brother Bill wrote:
>> ```
>> import std.stdio;
>>
>> immutable int[] i;
>>
>> shared static this() {
>> writeln("In shared static this()");
>> i ~= 43;
>> }
>>
>> void main()
>> {
>> writeln("In main()");
>> writeln("i: ", i);
>> }
>> ```
>>
>> Error messages:
>> C:\D\dmd2\windows\bin64\..\..\src\druntime\import\core\internal\array\appending.d(42): Error: cannot modify `immutable` expression `px`
>> px = (cast(T*)pxx.ptr)[0 .. pxx.length];
>> ^
>> c:\dev\D\31 -
>> 40\c33_3b_initialization_shared_static_this\source\app.d(7):
>> Error: template instance
>> `core.internal.array.appending._d_arrayappendcTX!(immutable(int[]), immutable(int))` error instantiating
>> i ~= 43;
>> ^
>> Failed: ["C:\\D\\dmd2\\windows\\bin64\\dmd.exe", "-v", "-o-",
>> "c:\\dev\\D\\31 -
>> 40\\c33_3b_initialization_shared_static_this\\source\\app.d",
>> "-Ic:\\dev\\D\\31 -
>> 40\\c33_3b_initialization_shared_static_this\\source"]
>>
>>
>> What changes are needed to get this to compile?
>> Is this syntax now obsolete? Is so, what has replaced it?
>
> ```
> 2.099.1 to 2.100.2: Success with output:
> -----
> In shared static this()
> In main()
> i: [43]
> -----
> ```
>
> version 100 was allot of safetyism changed
>
> this compiles and was probaly the intent:
> ```d
> import std.stdio;
>
> immutable(int)[] i;
>
> shared static this() {
> writeln("In shared static this()");
> i ~= 43;
> }
>
> void main()
> {
> writeln("In main()");
> writeln("i: ", i);
> }
> ```
Your changes do work, but at the cost of making i NOT deeply
immutable: no assignment, no changing any elements, no appending,
no setting length. This syntax permits appending and setting
length, with no assignment and no changing any elements.
The idea of shared static this() is that is has "special"
privileges to mutate immutable slices and other references.
These run prior to main, so it is "safe" to make mutations at
this early point.
I would like to execute the original code.
More information about the Digitalmars-d-learn
mailing list